在一个函数中用于多个表的 Attach() 方法 (laravel)

Attach() method for multiple tables in one function (laravel)

我觉得这个标题有点令人困惑,所以我会尽力解释一下。

我有什么

车型:

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();

控制器:保存汽车的方法,link它们到用户 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);
}

我正在尝试什么 understand/do

所以在我上面的控制器中,当用户想买车时,我可以附加用户 ID 和汽车 ID。

现在,如果用户想租车几个小时,我可以做同样的事情吗?假设我有一个带有下拉菜单的表单,显示用户想要汽车的时间。我可以在这个功能中保存用户和 he/she 想要租用的汽车包括时间吗?

这是否会将时间附加到用户感兴趣的汽车上,并且能够被 $user->id 调用以显示用户想要购买和租赁的所有汽车?

谢谢!

更新

感谢 Artur Subotkevič,我现在可以根据他的回答在 car_reservation pivot table 中保存汽车和预订的 ID。我尝试这样做以显示所有与此功能关联的时间的汽车

public function hour($id)
{

    $time = Car::with('reservations')->where('id',$id)->get();
    dd($time);
}

但我得到了这个观点

Collection {#364 ▼
   #items: []

} 我确定我有一些车 link 需要预订,我的预订车型现在是

  public function cars()
{
    return $this->belongsTo('Car','car_reservation');
}

不,这将无法正常工作。

但是有很多方法可以解决这类问题。

你应该说明你真正想做什么,我们可以给你正确的答案。


编辑

$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);

确保您在模型中设置了正确的关系:您需要在您的车型中设置预订关系