Laravel很多很多关系

时间:2014-06-12 15:31:38

标签: laravel-4

我开始使用Eloquent,我遇到了一个问题。我尝试设置多对多关系模式+模型。

以下是代码:

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片段:

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 个答案:

答案 0 :(得分: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);