php – Laravel 5.1在同一模型上有多对多关系

前端之家收集整理的这篇文章主要介绍了php – Laravel 5.1在同一模型上有多对多关系前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我看到在Laravel的ORM中纠结了以下内容

Scenerio:所有用户都有一个监视列表,监视列表包含其他用户.

我似乎无法让关系正常工作,因为它们是周期性的,到目前为止,我有以下内容

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');
    }
}

它并没有超越我期待的正确的形成.我错过了什么基本的东西?

解决方法

由于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','watched_id','user_id' );
    }
}

检查here获取有关多对多关系的更多信息

猜你在找的Laravel相关文章