Support the ongoing development of Laravel.io →
Database Eloquent

If I do this, I would be able to retrieve the images() for the item

$items = Item::all();
foreach($items as $item){
	$image = $item->images()->first();
}

However if I had a complex query using the query builder. I wouldn't be able to get the images() from it. Is there a way I could get the images using eager loading?

$items = Item::with("images")->join('users AS u', 'user_id','=','u.id')
          	->where('u.api_account_id', '=', '3d234')->get();	
foreach($items as $item){
	$image = $item->images()->first();
}

Objective

Select all items owned by users that has a specific api_account_id and eager loading the images that belong to the items retrieved.

Tables

items: id name user_id....
images: id item_id ...
users: id api_account_id firstname ...

Item Model

class Item extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'items';

	public function images()
	{
		return $this->hasMany('Image');
	}

	public function user(){
		
		return $this->belongsTo('User');
	}

}

Image model

class Image extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'images';

	public function item(){

		return $this->belongsTo('Item');
	}

}
Last updated 2 years ago.
0
$user_id = 1;
$api_account_id = 2;

$items = Item::with('images')->whereHas('user' => function($query) use($user_id, $api_account_id) {
    $query->where('user_id', '=', $user_id);
    $query->where('api_account_id', '=', $api_account_id);
})->get();

untested

Last updated 2 years ago.
0

Did you find a solution for this?

0

Sign in to participate in this thread!

Eventy

Your banner here too?

geocine geocine Joined 10 Feb 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.