Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

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!

Last updated 3 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 3 years ago.
0

Sign in to participate in this thread!

PHPverse

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.

© 2025 Laravel.io - All rights reserved.