[英]Laravel use where and multiple whereHas
I want to apply filter to User's posts with this code:我想使用以下代码将过滤器应用于用户的帖子:
$user = $request->userid;
$query = Post::query()
->where('post.owner.username', $username)
->when($request->filled('userid'), function (Builder $query) use ($user) {
$query->whereHas('tags', function (Builder $q) use ($user) {
$q->where('taggeduser.id', $user);
})->orWhereHas('comments', function (Builder $q) use ($user) {
$q->where('comment.owner.id', $user);
});
})
->when($request->filled('searchText'),
function (Builder $query) use ($username, $searchText) {
$query->whereRaw(['post.owner.username' => ['$eq' => $username]]);
$query->getQuery()->projections = ['score' => ['$meta' => 'textScore']];
$query->whereRaw(['$text' => ['$search' => $searchText]])->orderByDesc('post.taken_at_timestamp');
})
->when($request->filled('location'),
function (Builder $query) use ($location) {
$query->where('post.location.id', $location);
});
everything is fine except request has userid, it goes through ->when($request->filled('userid')
and the result is empty, I want to fetch users that has been tagged or commented in user's posts, giving userid to 'tags' and 'comments' relations, i have result in $q->where('taggeduser.id', $user);
一切都很好,除了请求有用户 ID,它通过->when($request->filled('userid')
并且结果为空,我想获取已在用户帖子中标记或评论的用户,将用户 ID 设置为' tags' 和 'comments' 的关系,我得到$q->where('taggeduser.id', $user);
but $query->get()
is empty.但是$query->get()
是空的。
try this尝试这个
$user = $request->userid;
$query = Post::where('post.owner.username', $username)
->when($request->filled('userid'), function (Builder $query) use ($user) {
$query->whereHas('tags', function (Builder $q) use ($user) {
$q->where('taggeduser.id', $user);
})->orWhereHas('comments', function (Builder $q) use ($user) {
$q->where('comment.owner.id', $user);
});
})
->when($request->filled('searchText'),
function (Builder $query) use ($username, $searchText) {
$query->whereRaw(['post.owner.username' => ['$eq' => $username]]);
$query->getQuery()->projections = ['score' => ['$meta' => 'textScore']];
$query->whereRaw(['$text' => ['$search' => $searchText]])->orderByDesc('post.taken_at_timestamp');
})
->when($request->filled('location'),
function (Builder $query) use ($location) {
$query->where('post.location.id', $location);
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.