Laravel 5.1同一个模型上的多对多关系

4

我似乎在Laravel的ORM中遇到了以下问题:

场景:所有用户都有一个观看列表,该列表包含其他用户。

由于关系是循环的,因此我似乎无法使关系正常工作,目前我有以下内容:

class UserWatchlist extends Model
{
    protected $table = 'UserWatchlist';

    public function Owner() {

        return $this->belongsTo('App\User');
    }

    public function WatchedUsers() {

        return $this->hasMany('App\User');
    }
}


    Schema::create('UserWatchlist', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('Users')->onDelete('cascade');

        $table->integer('watched_id')->unsigned();
        $table->foreign('watched_id')->references('id')->on('Users')->onDelete('cascade');
        $table->timestamps();
    });


class User extends Model
{


    public function Watchlist() {

        return $this->hasOne('App\UserWatchlist');
    }

    public function WatchedBy() {

        return $this->belongsToMany('App\UserWatchlist');
    }
}

它没有提取我期望的正确信息。我是否缺少一些基本知识?

1个回答

3

UserWatchlist是一个透视表,我想您可能面临一个多对多的关系,且关系的两个元素都是同一模型(User

如果是这种情况,您应该不需要为透视表UserWatchlist构建一个模型,而只需要通过透视表来设置用户之间的关系:

class User extends Model
{
    //get all the Users this user is watching
    public function Watchlist() 
    {   
        return $this->belongsToMany('User', 'UserWatchlist', 'user_id', 'watched_id'  );
    }

    //get all the Users this user is watched by
    public function WatchedBy() 
    {    
        return $this->belongsToMany('User', 'UserWatchlist', 'watched_id', 'user_id' );
    }
}

点击此处了解更多关于多对多关系的信息。


非常感谢,这完美地解决了问题。这是否意味着我不需要Watchlist模型? - Rookasaur
不需要 UserWatchlist 模型:您永远不必为中间表编写模型。 - Moppo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接