Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel eloquent relationship from query builder

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

}
like image 686
bman Avatar asked Oct 21 '22 14:10

bman


1 Answers

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();
}
like image 112
GWed Avatar answered Oct 23 '22 04:10

GWed