我有具有 hasMany 关系的 Posts 和 Comments 模型:
public function comments()
{
return $this->hasMany(Posts::class, 'posts_id', 'id');
}
在我的 Controller 中,我需要获取所有已发布的帖子 (is_published = 1),以及所有已发布的评论,且至少有 1 条已发布的评论:
$dbRecords = Posts::all()->whereStrict('is_published', 1);
$posts = [];
foreach ($dbRecords as $post) {
if (count($post->comments()) === 0) {
continue;
}
foreach ($post->comments() as $comment) {
if ($comment->is_published === 1) {
$posts[] = $post;
continue(2); // to the next post
}
}
}
但是,这样的解决方案很丑陋。另外,我将获得所有已发布的帖子,包括已发布和未发布的评论,因此我将强制在资源中再次过滤评论。
我发现的另一个解决方案 - 使用原始查询:
$dbRecords = DB::select("SELECT posts.*
FROM posts
JOIN comments ON posts_id = posts.id
WHERE posts.is_published = 1
AND comments.is_published = 1
HAVING count(posts.id) > 0;");
$users = array_map(function($row) { return (new Posts)->forceFill($row); }, $dbRecords);
但是并没有解决Resource中未发表评论需要过滤的问题。
最佳答案
- 在 Laravel eloquent 中使用
with
使用预加载来消除n+1
查询问题。 - 使用
has
或whereHas
函数来querying relationship existence .
在你的情况下,它会是这样的:
// Retrieve all posts that have at least one comment
$posts = Post::has('comments')->with('comments')->get();
// Retrieve posts with at least one comment and which are published
$callback = function($query) {
$query->where('is_published ', '=', '1');
}
$posts = Post::whereHas('comments', $callback)
->with(['comments' => $callback])
->where('is_published ', '=', '1')
->get();
关于php - Laravel 中的过滤关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64075342/