Laravel Eloquent关系从查询构建器

6
如果我这样做,我就可以检索到itemimages()
$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');
    }

}
1个回答

3

您还没有实际执行查询。请添加get(),all()或first()

此外,您实际上不会返回一个Eloquent模型,因此将无法使用Eloquent关系。但是,您可以将流畅的查询添加到Eloquent中。请尝试以下内容:

$items = Item::join('users AS u', 'i.user_id', '=', 'u.id')
              ->where('account_id', '=', 5)
              ->all();       
foreach($items as $item){
    $image = $item->images()->first();
}

是的,抱歉我在复制粘贴时忘记添加 all() 了,因为我有一系列的 ->where()。这对 $item->images()->first() 有效,但对 $item->user->name 无效,你有什么想法吗?我收到一个错误 Trying to get property of non-object - bman
$item->user()->first()->name - GWed
我更新了我的模型。每个项目只有1个用户,如果我只是使用$item = Item::all();,那么$item->user->name就可以工作。你有什么想法吗? - bman
你确定吗?没有看到你的模型,我无法确定,但是从$item = Item::all();来看,$item->user->name似乎不太可能起作用。原因是$item->user应该返回一个Eloquent属性,通常是一个字符串。所以$item->user->name试图调用一个字符串的对象属性,这将抛出一个错误——尝试获取非对象的属性。 - GWed
如果你想获取一个项目的用户名,我唯一能想到的方法是这样的 - $item->user()->first()->name - GWed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,