Laravel 5 多个附加

Laravel 5 multiple attach

我有 table 和来自其他列的 3 个 ID。如何附加超过 2 个 ID?我 不知道如何连接三把钥匙。当我尝试执行“$weather->parks()->attach('1')->users()->attach('2');”时它不附加 park_id。 请帮助。

Schema::create('weather_user_park', function (Blueprint $table) {
        $table->integer('weather_id')->unsigned();
        $table->integer('park_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->foreign('weather_id')->references('id')->on('weathers');
        $table->foreign('park_id')->references('id')->on('parks');
        $table->foreign('user_id')->references('id')->on('users');
    });

我还有3个模特:

Park.php

public function weathers()
{
    return $this->belongsToMany('App\Weather', 'weather_user_park');
}

    public function users()
{
    return $this->belongsToMany('App\User', 'weather_user_park');
}

User.php

public function weathers()
{
    return $this->belongsToMany('App\Weather', 'weather_user_park');
}

    public function parks()
{
    return $this->belongsToMany('App\Park', 'weather_user_park');
}

Weather.php

       public function users()
{
    return $this->belongsToMany('App\User', 'weather_user_park');
}

    public function parks()
{
    return $this->belongsToMany('App\Park', 'weather_user_park');
}

您可以通过向附加方法添加第二个参数来实现。

$weather->parks()->attach(1, [
    'user_id' => 2,
]);

https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships https://laravel.com/docs/5.4/eloquent-relationships#many-to-many(尤其是 "Retrieving Intermediate Table Columns" 部分)

Park.php

public function users()
{
    return $this->belongsToMany('App\User', 'park_user')->withPivot('weather');
}  

User.php

public function parks()
{
    return $this->belongsToMany('App\Park', 'park_user')->withPivot('weather');
}

park->users(); 给你公园的信息

您可以像这样向用户添加信息:

$park = App\Park::find(1);
$weather = App\Weather::find($id);
$user->parks()->attach($park->id, ['weather' => $weather->id]); 

删除关系

$user->parks()->detach($park->id);