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);
but $query->get()
is empty.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.