T
T
Troodi Larson2021-03-12 14:10:44
Laravel
Troodi Larson, 2021-03-12 14:10:44

How to select records through where the relation has a condition?

Greetings, I read the documentation, but I did not find what I needed.
There are 2 tables: The first has a link to the second.
Example (type_id | int:255) -> Types (id | int:255, name | string)
Need to pull all records from Example where type_id is equal to id from type table where name = 'example'.
That is, in the type table we are looking for the name 'example', it will have id == 3, for example. And already Example is looking for type_id == 3.
The question itself is how to do this using the Example model and its relations.

Example::where('types', function ($query) {
            $query->select('id')
                ->from(with(new Type())->getTable())
                ->where('name', 'пример');
        })->get();


That is, in this case, it can be described in this way. But I would like to find a beautiful option with an attitude.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N, 2021-03-12
@Fernus

// types - это отношение один ко многим

$rs = Example::whereHas('types', function($q) {
    $q->where('name', 'пример');
})->get();

Documentation with examples

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question