2013-10-22 27 views
0

我想獲取所有類的條目,其中有一些條件屬性。一個關係,標籤,應該急切加載。Laravel多對多急切加載總是返回空結果

的模型看起來像雙外鍵,entry_id,TAG_ID所以

class Tag extends Eloquent { 
    protected $table = 'tags'; 
    protected $guarded = array(); 
    public function entries() 
    { 
     return $this->belongsToMany('Entry'); 
    } 
} 

class Entry extends Eloquent { 
    protected $table = 'entries'; 
    protected $guarded = array(); 
    public function tags() 
    { 
     return $this->belongsToMany('Tag'); 
    } 

    public function user() 
    { 
     return $this->belongsTo('User'); 
    } 

    public function votes() 
    { 
     return $this->hasMany('Votes'); 
    } 
} 

表entry_tag,存在。

我正嘗試使用此代碼。 (1)

$testEntries = Entry::with(array('tags' => function($query) 
{ 
    $query->where('tag_id', '=', '1'); 
}))->get(); 

但是,它沒有返回。 即使使用下面的代碼也會產生完全的zilch。 (2)

$testEntries = Entry::with('tags')->get(); 

檢查數據庫日誌,我可以看到,查詢都OK。它們產生 (3)

select `tags`.*, `entry_tag`.`entry_id` as `pivot_entry_id`, `entry_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `entry_tag` on `tags`.`id` = `entry_tag`.`tag_id` where `entry_tag`.`entry_id` in (?, ?, ?, ?, ?, ?, ?, ?)","bindings":["1","2","3","4","5","6","7","8"] 

手動執行查詢時(4)

select `tags`.*, `entry_tag`.`entry_id` as `pivot_entry_id`, `entry_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `entry_tag` on `tags`.`id` = `entry_tag`.`tag_id` where `entry_tag`.`entry_id` in (?, ?, ?, ?, ?, ?, ?, ?) and `tag_id` = ?","bindings":["1","2","3","4","5","6","7","8","1"] 

其中兩個工作(並且發現結果)。

我錯過了什麼?我現在幾個小時就撓了腦袋!

編輯:

我已經試過顯示結果,沒有任何運氣,像下面

Log::debug('testing fetching entries:: ' . json_encode($testEntries)); 

foreach(Entry::with('tags')->get() as $entry) 
     { 
      Log::debug('test1!! ' . json_encode($entry));   
     } 

編輯2: 我曾嘗試用他們的條目獲取標籤,如

Tag::with('entries')->get(); 

但它(連同其他組合)每次都返回零結果。我想也許我已經錯過了我設置牌桌的方式。這裏是完整的sql輸出嘗試(2),以防萬一。

{"query":"select * from `entries`","bindings":[],"time":0.33},{"query":"select `tags`.*, `entry_tag`.`entry_id` as `pivot_entry_id`, `entry_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `entry_tag` on `tags`.`id` = `entry_tag`.`tag_id` where `entry_tag`.`entry_id` in (?, ?, ?, ?, ?, ?, ?, ?)","bindings":["1","2","3","4","5","6","7","8"],"time":0.74} 
+0

不確定這是否有幫助,但嘗試定義您的BelongsToMany()關係,如下所示:'return $ this-> belongsToMany('Entry','entry_tag','entry_id','tag_id');'and vice在Entry表中輸入 –

+0

你如何試圖顯示結果?也許在那裏有一個錯字。 – user1669496

+0

@GladToHelp,沒有變化。由於它目前創建了成功的SQL查詢(查看數據庫日誌),所以沒有什麼區別。 –

回答

0

如果使用軟刪除特質,檢查deleted_at有默認值NULL