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
謝謝你,我確實知道get()返回其中username匹配和第()將只返回第一次出現的所有行,但我不知道這一點是個例外:) – tsm
不同之處在於'get'總是返回一個'Collection'(如果沒有數據,它可能是空的),如果沒有數據,'first'返回'Model'或'null'。 –