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

时间:2016-12-13 20:50:43

标签: laravel model eloquent many-to-many laravel-5.3

我认为标题有点令人困惑,所以我会尽力解释这个。

我有什么

车型:

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调用以显示用户想要购买和租赁的所有汽车吗?

谢谢!

更新

感谢ArturSubotkevič我现在可以根据他的回答在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');
}

1 个答案:

答案 0 :(得分:1)

不,这不会正常工作。

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

你应该解释你真正想做的事情,我们可以给你正确答案。

修改

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

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