2014-06-12 45 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'。 –