简体   繁体   中英

How to get a list of users who liked post using Eloquent ORM?

I have a Post Model that has a Polymorphic Relation to a Likes model by way of this function:

public function likes() {
  return $this->morphMany('App\Models\Like', 'likeable');
}

Back in my Likes model:

public function likeable() {
  return $this->morphTo();
}

UPDATE

the likes() method returns a collection like so:

  [  
   {  
      "id":125,
      "user_id":30,
      "likeable_id":1,
      "likeable_type":"App\Models\Post",
      "created_at":"2017-10-13 22:06:13",
      "updated_at":"2017-10-13 22:06:13"
   },
   {  
      "id":126,
      "user_id":17,
      "likeable_id":1,
      "likeable_type":"App\Models\Post",
      "created_at":"2017-10-13 22:06:13",
      "updated_at":"2017-10-13 22:06:13"
   }
  ]

Now i want to create another function in my Post model that gets each User associated with the user_id of each like object in the returned collection, i've written this so far:

public function likeUsers($post) {
  $likes = $post->Likes();
  foreach ($likes as $like) {
    $user = User::find($like->user_id);
    $name = $user->first_name;
    // Here is where i want to push the $name var into a new collection  

  }
   //return new Collection;
}

How do I push the each $name var in my foreach into a new Eloquent collection and return that?

You shouldn't call getLikes() directly on your model. Instead, you should access getLikes attribute:

foreach ($post->getLikes as $like) {
  //$like will contain a model that likes the post
}

I also suggest you change the method name from getLikes() to likes() . It's not a getter but a relation definition and the convention is to name such a method the way you'd name a relation. Then you should be able to access models that like your post with $post->likes .

BTW, are you going to have any other model like your posts except Users? If not, you don't need a polymorphic relation for that, belongsToMany should be enough.

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