Laravel 5.1 Lots of many for many relationships on the same model

I saw how he got confused in Laravel ORM with the following:

Scenerio: all users have a watchlist, the watchlist contains other users.

I can not seem that the relations work correctly, since they are cyclical, so far I have the following:

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

It does not pull through the correct form that I expect. Am I missing something fundamental?

+4
source share
1 answer

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

" "

+3

Source: https://habr.com/ru/post/1616528/


All Articles