Back

"with" clause with attributes returning empty results.


Gideon King posted 3 months ago

I am trying to retrieve a specific attribute from a one to many relationship using "with".

Booking::with('bookingLines')->first();

gets me the booking with an array of booking lines. All good.

Booking::with('bookingLines:id,booking_type')->first();

gets me the booking with an empty array where the booking lines should be. Even just including the id attribute doesn't work, and neither does using bookingLines:booking_lines.id.

I have successfully used this style of with clause in many to many relationships. What am I missing here?

Gideon King replied 3 months ago

Never mind, found the solution. In a one to many relationship you have to include the foreign key in the with clause. I saw no mention of this in the documentation.

Here is what worked:

Booking::with('bookingLines:id,booking_id')->first();

Hope this helps someone else.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us