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 to get all the relationship data from the Eloquent Models considering this is a query builder?
$items = DB::table('items as i')
->join('users AS u', 'i.user_id', '=', 'u.id')
->where('account_id', 5)->all();
foreach($items as $item){
$image = $item->images()->first();
}
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');
}
}
UPDATED: Added User Model
class User extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
public function items()
{
// foreign key outside using this pk
return $this->hasMany('Item');
}
}
You haven't actually executed the query. Add get(), all() or first()
Additionally, you won't actually be returning an eloquent model so won't be able to use eloquent relationships. You can just add fluent queries to eloquent though. Try this:
$items = Item::join('users AS u', 'i.user_id', '=', 'u.id')
->where('account_id', '=', 5)
->all();
foreach($items as $item){
$image = $item->images()->first();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With