来自查询构建器的 Laravel 雄辩关系

bma*_*man 5 php mysql laravel-4

如果我这样做,我将能够检索images()item

$items = Item::all();
foreach($items as $item){
    $image = $item->images()->first();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用查询构建器进行复杂查询。我将无法从中得到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();
}
Run Code Online (Sandbox Code Playgroud)

物品型号

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

}
Run Code Online (Sandbox Code Playgroud)

图像模型

class Image extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'images';

    public function item(){

        return $this->belongsTo('Item');
    }

}
Run Code Online (Sandbox Code Playgroud)

更新:添加用户模型

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

}
Run Code Online (Sandbox Code Playgroud)

Gaz*_*dge 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();
}
Run Code Online (Sandbox Code Playgroud)