Answer the question
In order to leave comments, you need to log in
How to correctly compose a query with withTrashed?
Hello!
I have such a task:
- There are comments to each news.
- There are answers to these comments, which are displayed in the form of a ladder.
- There is a soft deletion of comments.
You need to make a query to display more and deleted comments only if they already have replies. If there are no answers, then no output is required.
At first I tried like this:
$comments = $article->comments()->where(function ($query) {
$query->where('comment_id', 0);
$query->orWhereNull('comment_id');
})->where(function ($query) {
$query->whereHas('comments', function ($query) {
$query->withTrashed();
});
$query->orWhereDoesntHave('comments');
})->orderBy('id', 'desc')->paginate($this->paginate);
$comments = $article->comments()->withTrashed()->where(function ($query) {
$query->where('comment_id', 0);
$query->orWhereNull('comment_id');
})->where(function ($query) {
$query->whereHas('comments');
$query->orWhereDoesntHave('comments', function ($query) {
$query->whereNull('deleted_at');
});
})->orderBy('id', 'desc')->paginate($this->paginate);
Answer the question
In order to leave comments, you need to log in
->where(function ($query) {
$query->where('deleted_at', '!=', null)->has('comments');
});
->orWhere('deleted_at', '=', null)
I did this using the _lft _rgt indexes.
First I got just the parent comments, then I got all the comments between the parent indexes inclusive, with the condition whereHas('comments') that have children that are not deleted.
And in js I already translated it into a tree, well, or you can in the same place in php
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question