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');
}
}
all()了,因为我有一系列的->where()。这对$item->images()->first()有效,但对$item->user->name无效,你有什么想法吗?我收到一个错误Trying to get property of non-object。 - bman$item = Item::all();,那么$item->user->name就可以工作。你有什么想法吗? - bman