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'。 –