jeudi 6 décembre 2018

Laravel returns a Collection with duplicates of the first model

I'm developing a Laravel 5.7 (API) application with a PostgreSQL database behind it. The relevant Models are: User (customers and employees), Car, and Request.

An employee User creates a Request for a Car, that belongs to a customer User.

The relationships are:

  • Car (as customer) : User = n:m
  • Car : Request = 1:n
  • User : Request (as employee) = 1:n

enter image description here

(The data design is suboptimal, to put it mildly, but anyway, it's the given reality for now.)

Now to the actual issue. I want to display all Requests of a customer User:

Request::query()
    ->join('user_car', 'user_car.car_id', '=', 'request.car_id')
    ->join('user', 'user.id', '=', 'user_car.user_id')
    ->where('user.id', '=', $customer->id)
    ->select()
    ->get();

The customer with the given $customer->id has n Requests. And the length of the result Collection of the call above is correct. But all these n entries are duplicates of the first one. Means: I'm getting a list with n instances of Request#1.

The query is correct. I logged the database, got the generated query

SELECT *
FROM "request"
INNER JOIN "user_car" ON "user_car"."car_id" = "request"."car_id"
INNER JOIN "user" ON "user"."id" = "user_car"."user_id"
WHERE "user"."id" = 1

..., and executed it manually. The result table contains as expected n different entries.

I found a workaround. This call

Request::whereIn('car_id', $customer->cars()->pluck('id')->toArray())->get();

... retrieves the expected set of model.

But nevertheless: Why does the first call return a list of references to the same Model object? Is it a (known) bug?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Po29mE
via IFTTT

Aucun commentaire:

Enregistrer un commentaire