根据多对多关系检索雄辩模型



假设我有一个博客模型、帖子模型和照片模型。

  • 一个博客可以有很多帖子
  • 帖子属于博客
  • 帖子属于许多照片
  • 一张照片属于许多帖子
posts Table
id | blog_id | text
photos Table
id | text
photo_post Table
post_id | photo_id

我想做的是在指定的博客上找到一个特定的帖子,上面有两张特定的照片

我正在努力与Eloquent一起检索这张Post记录。

$post = Post::where('blog_id', $blog->id)
->whereHas('photos', function($q) {
$q->where('photo_id', 180)->where('photo_id', 181);
})->firstOrFail();

每个博客只有一个例子,在一篇文章中使用这两张照片。

有什么建议吗?

您可以使用whereIn

$post = Post::where('blog_id', $blog->id)
->whereHas('photos', function($q) {
$q->whereIn('photo_id', [180, 181]);
})
->firstOrFail();

最新更新