问题
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');
}
}
回答1:
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();
}
来源:https://stackoverflow.com/questions/21874390/laravel-eloquent-relationship-from-query-builder