O
O
on_click2021-06-25 21:38:34
Laravel
on_click, 2021-06-25 21:38:34

How to limit the whereIn selection to 1 entry for each value from the passed array?

Greetings!

Let's say there are 3 main comments in the database, each of these comments has a certain number of replies to them. The fact that this is a response and not a "parent" comment is indicated by the child_id field (it contains the id of the main comment).

$id_list = [1,2,3]; // id родительских комментариев
$replies = Comment::whereIn('child_id',  $id_list)->get();

This is how I get all replies to those comments.

Can you please tell me how to limit this selection to one response to each of the parent comments (so that in the end there are a maximum of 3 entries in $replies)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-06-25
@on_click

make hasone attitude reply in comment. then use with - Comment with reply.
It's just not clear why there is a parent comment in child id. seems to be called differently.

P
pLavrenov, 2021-06-25
@pLavrenov

1) The relationship between parent and child hasMany (the relation of the model to the same model can only be set through the child_id key)
2) Get the relationship

Model::whereIn('id', [1,2,3])->with([
    'relation_name' => function($query) {
         $query->take(1);
    }
])->get()->pluck('relation_name');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question