[英]laravel eloquent relationship from query builder
如果我这样做,我将能够检索该item
的images()
$items = Item::all();
foreach($items as $item){
$image = $item->images()->first();
}
但是,如果我使用查询构建器进行了复杂查询。 我无法从中获取images()
。 考虑到这是一个查询构建器,有没有办法从Eloquent模型中获取所有关系数据?
$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();
}
项目模型
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');
}
}
图像模型
class Image extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'images';
public function item(){
return $this->belongsTo('Item');
}
}
更新:添加了用户模型
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');
}
}
您还没有真正执行过查询。 添加get(),all()或first()
此外,您实际上不会返回一个雄辩的模型,因此无法使用雄辩的关系。 您只需添加流畅的查询即可。 尝试这个:
$items = Item::join('users AS u', 'i.user_id', '=', 'u.id')
->where('account_id', '=', 5)
->all();
foreach($items as $item){
$image = $item->images()->first();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.