我正在努力处理 Eloquent 查询。我的最终目标是列出任何人创作的所有公共(public)帖子,以及由给定用户在给定出版物中创作的私有(private)帖子。
示例:
给出这 3 个帖子
标题:标题 1 | user_id: 1 | is_private: true
标题:标题 2 | user_id: 2 | is_private: 假
标题:标题 3 | user_id: 3 | is_private: true
userId 1 的输出应该是:
标题 1 和标题 2
我最擅长的是以下内容:
$posts = Post::where('publication_id', $publicationId)
->where('is_private', false)
->where(function ($query) {
$query->where('owner_id', auth()->id())
->where('is_private', true);
});
我知道这离需要的还很远。
最佳答案
如果将第二个 where 语句更改为 orWhere
可能会起作用
$posts = Post::where('publication_id', $publicationId)
->where('is_private', false)
->orWhere(function ($query) {
$query->where('owner_id', auth()->id)
->where('is_private', 'true');
});
原因是第一个 where 将限制第二个 where 仅搜索公共(public)帖子以检查私有(private)帖子。这不会产生预期的结果。
祝一切顺利
关于laravel - Eloquent 查询以列出项目可见性约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449124/