我有来自其他列的带有3个ID的表。如何附加两个以上的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');
});我还有三种型号:
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');
}发布于 2017-02-15 21:44:16
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);发布于 2017-02-15 20:13:28
您可以通过添加第二个参数来附加方法来做到这一点。
$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 (特别是“检索中间表列”部分)
https://stackoverflow.com/questions/42258803
复制相似问题