Back

Eager Loading + Join


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');
	}

}
$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

Did you find a solution for this?


Sign in to participate in this thread!


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