laravel eloquent relationship from query builder

感情迁移 提交于 2020-06-27 11:27:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!