laravel雄辩的关系,从查询生成器 [英] laravel eloquent relationship from query builder

查看:94
本文介绍了laravel雄辩的关系,从查询生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果执行此操作,我将能够检索item

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();
}

但是,如果我使用查询生成器进行复杂查询.我将无法从中获取images().考虑到这是一个查询生成器,是否有办法从雄辩模型中获取所有关系数据?

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();
}

项目模型

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()

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();
}

这篇关于laravel雄辩的关系,从查询生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆