A
A
Anton2019-03-07 11:33:34
Laravel
Anton, 2019-03-07 11:33:34

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);

Did not work. Then I tried like this:
$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);

It didn't work either. No ideas yet. I ask those who know to help me with this request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
NubasLol, 2019-03-07
@Yadalay

->where(function ($query) {
    $query->where('deleted_at',  '!=',  null)->has('comments');
});
->orWhere('deleted_at',  '=',  null)

A
Anton Shelestov, 2019-03-07
@ShelestovAnt

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 question

Ask a Question

731 491 924 answers to any question