2014-02-19 209 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