2014-06-12 246 views
0

我開始使用Eloquent,並且遇到了問題。我試圖建立一個多對多的關係模式+模型。Laravel多對多關係

下面是代碼:

routes.php snippet: 
$user1 = User::findOrFail(1); 
$user2 = User::where('username', '=', 'TestUser')->get(); 
// we make $user1 to follow $user2 
$user1->followedBy()->save($user2); 

用戶模型片段:

public function followedBy() { 
    return $this->belongsToMany('User', 'user_follows', 'user_id', 'follow_id'); 
} 

public function following() { 
    return $this->belongsToMany('User', 'user_follows', 'follow_id', 'user_id'); 
} 

DB模式片段:

Schema::create('user_follows', function(Blueprint $table) 
     { 
      $table->increments('id'); 
      $table->integer('user_id'); 
      $table->integer('follow_id'); 
      $table->timestamps(); 
     }); 

我得到的錯誤,當我參觀路線:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in /Applications/MAMP/htdocs/Laravel/proj2/app/routes.php on line 84 and defined 

回答

1

錯誤說明了一切:

$user2 = User::where('username', '=', 'TestUser')->get(); 
// returns Collection 

你需要這個來代替:

$user2 = User::where('username', '=', 'TestUser')->first(); 
// returns single Model 

順便說一句:

// we make $user1 to follow $user2 
$user1->followedBy()->save($user2); 

$user2遵循$user1和使用這個:

$user1->followedBy()->attach($user2); 

對於save先保存$user2型號,這裏是多餘的。它是在這種情況下使用:

$user2 = new User; 
// assign some properties 
... 
$user1->followedBy()->save($user2); 
+0

謝謝你,我確實知道get()返回其中username匹配和第()將只返回第一次出現的所有行,但我不知道這一點是個例外:) – tsm

+0

不同之處在於'get'總是返回一個'Collection'(如果沒有數據,它可能是空的),如果沒有數據,'first'返回'Model'或'null'。 –