Laravel 5多个附加
问题描述:
我有其他列3 ID的表。如何附加2个以上的ID?我 不知道如何附加thoes三个键。当我尝试做“$ weather-> parks() - > attach('1') - > users() - > attach('2');”它不附加park_id。 请帮助。Laravel 5多个附加
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');
}
答
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);
答
您可以通过向attach方法添加第二个参数来实现。
$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(特别是 “检索中间体表列” 一节)
你尝试没有链接这样的方法呢?并分别打电话给它? – Gntem