2014-06-30 16 views
0

嘿傢伙你怎麼樣? 我試圖簡單地通過id找到,並同時保證關係表中的列是一個值。 我嘗試了一些東西,但沒有任何作品。雄辯的ORM通過id找到並添加where子句到一個關係模型

$tag = Tag::find($id)->whereHas('posts', function($q){ 
    $q->where('status','=', 1); 
})->get(); 

另外:

$tag = Tag::whereHas('posts', function($q) { 
    $q->where('status','=', 1); 
})->where('id','=', $id)->get(); 

你能幫助我嗎?

這是一個簡單的事情,但我不能設法做...

回答

0

你檢查Query Scope

你可以這樣做:

$tag = Tag::where('status', '=', 1) 
      ->where('id', '=', 1, $id) 
      ->get(); 
+0

狀態字段在Post模式中...他們有多對多的關係...我可以從特定標記中獲取帖子,但是我想要的只是獲取status = 1 –

+0

的帖子,如果您想要只是狀態= 1的帖子,爲什麼不使用Post :: where('status','=','1')'? –

+0

因爲我需要來自特定標記ID的帖子 –

1

您需要在Eloquent文檔閱讀。瞭解什麼是find,first,get

你的代碼做你需要什麼,並更多的(雖然有點錯誤);)

$tag = Tag::find($id) // here you fetched the Tag with $id 
     ->whereHas('posts', function($q){ // now you start building another query 
    $q->where('status','=', 1); 
})->get(); // here you fetch collection of Tag models that have related posts.status=1 

所以,這是你想要什麼:

$tag = Tag::whereHas('posts', function($q){ 
    $q->where('status','=', 1); 
})->find($id); 

它將返回Tag模型或null如果不存在與where子句或$id相匹配的行。

+0

該代碼沒有工作...返回null,我有標籤...這是它工作的唯一方式:[code] $ tag = Tag :: find($ id); $ posts = Post :: whereHas('tags',function($ q)use($ id) { $ q-> where('id','=',$ id); }) - > where('status','=','1') - > get(); –

+0

你粘貼的是完全不同的查詢。我給你的那個可能會返回null,就像答案中所述。 –