Laravel 4 雄辩的ORM按id查找并将where子句添加到关系模型中

Laravel 4 雄辩的ORM按id查找并将where子句添加到关系模型中,laravel-4,eloquent,Laravel 4,Eloquent,嘿,伙计们,你好吗? 我试图简单地按id查找,同时保证关系表中的列具有值。 我尝试了一些方法,但没有任何效果 $tag = Tag::find($id)->whereHas('posts', function($q){ $q->where('status','=', 1); })->get(); 此外: 你能帮我吗 这是件简单的事,但我做不到…你检查过了吗 您可以这样做: $tag = Tag::where('status', '=', 1) -

嘿,伙计们,你好吗? 我试图简单地按id查找,同时保证关系表中的列具有值。 我尝试了一些方法,但没有任何效果

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

你能帮我吗

这是件简单的事,但我做不到…

你检查过了吗

您可以这样做:

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

你需要阅读有说服力的文档。了解这方面的
查找
首先
获取

您的代码可以满足您的需要,还有更多(尽管有点错误);)

这就是你想要的:

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

如果没有与
where
子句或给定的
$id

匹配的行,它将返回
Tag
model或
null
。。。他们有一种多对多的关系。。。我可以从特定标记获取帖子,但我想要的是只获取状态为1的帖子如果只需要状态为1的帖子,为什么不使用
Post::where('status','=','1')
?因为我需要特定标签ID中的帖子,所以
标签
帖子
之间是否存在一对多关系?代码不起作用。。。返回null,我有标签。。。这是它工作的唯一方式:[code]$tag=tag::find($id)$posts=Post::whereHas('tags',function($q)use($id){$q->where('id','=',$id);})->where('status','=','1')->get();您粘贴的是完全不同的查询。我给你的那个可能会返回null,就像回答中所说的那样。
$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);