M
M
mrSeller2018-03-18 17:28:59
Laravel
mrSeller, 2018-03-18 17:28:59

I can't get a selection through Eloquent Laravel - how to write a query correctly?

There are tables users and transports.
When fetching a vehicle, you need to check the city_id of the user to which the vehicle belongs, in order to get the vehicle only in a specific city.

users
  id
  city_id
transports
  id
  user_id

After thinking and looking through the docks, I built the following query:
$transport = Transport::with(['user' => function ($query) use ($city_id) {
  $query->where('city_id', $city_id);
}]);

And it seemed to work, but then I realized that users with such a city_id were selected, and not transport (although there was already one user).
Pokumekav and looking through the docks, I could not think of anything.
How then to register request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
anlamas, 2018-03-18
@mrSeller

whereHas('user', fucntion($query) use ($city_id) {
    $qeury->where('city_id', $city_id);
})

I don’t know how you looked, but here is
Querying Relationship Existence

I
Ilya Parshakov, 2018-03-19
@parschakov

try whereHas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question