I have three tables:
1. Users Table
field: user_id
2. Likes Table
field: item_id, user_id
3. Items Table
field: item_id, profile_pic_url
When an array of items is take from the database, I want to access the likes table to find which users liked it. I then want to get the information about these users, for example, the profile picture url.
//Getting the items from the database
$items = Category::orderByRaw("RAND()")
->take(9)
->get();
This all I have. I am clueless on what to do next. And thanks in advance! Please comment if you have any questions!
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/>';
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community