简体   繁体   中英

Polymorphic relation in laravel for following a user

I've a User model and a likes table. I applied polymorphic relation to it.

likes table has the following structure:

user_id --- likeable_id ---- likeable_type
eg: 1 ---- 5 ---- App\User  //This indicates user 1 follows 5
eg: 3 ---- 1 ---- App\User  //This indicates user 3 follows 1

Now I'm trying to get the followers and following list.

In the User model I added

 public function likes()
  {
        return $this->morphMany(Like::class, 'likeable');
  }

    public function followers()
    {
        return $this->belongsTo('App\Like', 'likeable_id', 'user_id');
    }

and from the controller, I've tried to do this:

$user1 = User::with('followers')->where('username', $username)->first();

But it's returning null for the followers relation. Am I doing it right?

Got the answer by myself: In User model -

public function followers()
{
    return $this->morphMany('App\Like', 'likeable')->with('user');
}

public function following()
{
    return $this->morphMany('App\Like', 'user', 'likeable_type')->with('user');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM