Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

Instead of making multiple joins everywhere in your project, define a relationship.
This is a nice example of a Many-to-Man relationship.

class Item...
public function likers(){
return $this->belongsToMany('User', 'likes_table');
}

Use the relationship to retrieve users for the item.

$usersWhoLikeThisItem = $item->likers()->get();

or the shortcut form

$usersWhoLikeThisItem = $item->likers;

You can also use eager loading to make your project faster.

$newItems = Item::with('likers')->where('created_at', '>', $time)->get();
foreach($newItems as $newItem)
{
  $likers = $newItem->likers;//already loaded
  foreach($likers as $user){
    echo 'PictureLink:'.$user->profile_picture_url.'<br/>';
  }
}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

amilajack amilajack Joined 19 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.