我认为标题有点混乱,所以我会尽力解释这一点。
我有什么
汽车型号:
public function users()
{
return $this->hasMany('User','car_user');
}用户模型
public function cars()
{
return $this->belongsToMany('App\Models\Access\Car','car_user');
}预约模型
public function cars()
{
return $this->belongsToMany('App\Models\Access\Car','car_user');
}汽车迁移:
$table->increments('id');
$table->string('name')->nullable();
$table->string('age')->nullable();
$table->string('model')->nullable();用户迁移:
$table->string('street')->nullable();
$table->string('niehgborhood')->nullable();
$table->string('city')->nullable();
$table->increments('id');
$table->string('name')->nullable();car_user:
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('car_id')->unsigned();
$table->foreign('car_id')->references('id')->on('cars');保留:
$table->increments('id');
$table->string('from_date')->nullable();
$table->string('to_date')->nullable();
$table->string('from_time')->nullable();
$table->string('to_time')->nullable();控制器:保存汽车并将其链接到用户id的方法:
public function store(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
$new_car = new Car();
$new_car->name = $request->name;
$new_car->age = $request->age;
$new_car -> model = $request->model;
$new_car->save();
$id = $new_cars->id;
$user->cars()->attach($id);
}我想要理解的东西/做
所以在我上面的控制器中,当用户想要购买汽车时,我可以用汽车id附加用户id。
现在,如果用户想租几个小时的车,我能做同样的事情吗?假设我有一个带有下拉菜单的表单,显示用户想要汽车的时间。我可以节省用户和他/她想租车的时间,包括这个功能的所有时间吗?
这会把时间附加到用户感兴趣的汽车上,并且能够被$user->id调用来显示用户想要购买和出租的所有汽车吗?
谢谢!
更新
多亏了Artur Subotkevič,我现在可以根据他的答案在car_reservation枢轴表中保存汽车的id和预订。我尝试这样做,以显示所有与此函数相关的时间的汽车。
public function hour($id)
{
$time = Car::with('reservations')->where('id',$id)->get();
dd($time);
}但我明白这个观点
Collection {#364 ▼
#items: []}我肯定有几辆车与预订相关联,我的预订模式现在是
public function cars()
{
return $this->belongsTo('Car','car_reservation');
}发布于 2016-12-13 21:12:26
不,这不能正常工作。
但是有很多方法可以解决这些问题。
你应该解释你到底想做什么,我们可以给你正确的答案。
编辑
$user = JWTAuth::parseToken()->authenticate();
$new_car = new Car();
$new_car->name = $request->name;
$new_car->age = $request->age;
$new_car->model = $request->model;
$new_car->save();
$time = new Reservation();
$time->from_date = $request->from_date;
$time->to_date = $request->to_date;
$time->from_time= $request->from_time;
$time->to_time = $request->to_time;
$time->save();
// Attach the reservation to the car's reservations
$new_car->Reservation()->attach($time->id);
// Attach the car to the user cars
$user->cars()->attach($new_car->id);确保您在您的模型中设置了正确的关系:,您需要在您的汽车模型中有预订关系。
https://stackoverflow.com/questions/41130317
复制相似问题