2014-02-19 120 views
2

如果我这样做,我将能够检索images()itemlaravel雄辩关系

$items = Item::all(); 
foreach($items as $item){ 
    $image = $item->images()->first(); 
} 

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

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

} 

回答

2

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

此外,您实际上不会返回雄辩模型,因此无法使用雄辩关系。虽然你可以添加流利的查询来提供口才。试试这个:

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

对不起,我忘了在复制粘贴时添加'all()',因为我有一系列' - > where()'。这适用于'$ item-> images() - > first()',但不适用于'$ item-> user-> name'的任何想法?我得到一个错误'试图获取非对象的属性' – bman

+0

$ item-> user() - > first() - >名称 –

+0

我更新了我的模型。如果我简单地执行'$ item = Item :: all();',则每个Item只有1个用户,'$ item-> user-> name'可以工作。你有什么想法? – bman