2017-02-15 101 views
0

我有其他列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'); 
} 
+0

你嘗試沒有鏈接這樣的方法呢?並分別打電話給它? – Gntem

回答

0

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