laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.69k stars 11.05k forks source link

Polymorphic eager loading with select not working (correctly) #2966

Closed rogierborst closed 10 years ago

rogierborst commented 10 years ago

I have three tables, 'actors', 'series' and 'movies'. An actor can belong to many series and/or many movies, and both movies and series can have many actors. Good case for a polymorphic many-to-many relationship.

When I query all movies, I wish to eager load all actors, but only their first and last names. For this I do the following:

return Movie::with(array('actors' => function($query){
    $query->select('first_name', 'last_name');
}))->get();

This however still loads ALL columns for actors, since the resulting query is this one:

// showing only the relevant part of the query that was built
... select `first_name`, `last_name`, `actors`.* ... from `actors`

The issue here, is that the columns I requested (first_name and last_name) are indeed inserted into the query (first two fields), but then the actors.*` is automatically added, which obviously loads the rest of the columns as well.

I'm not smart enough to figure out how Laravel actually builds this query, so I'm not at all able to contribute with a pull request. Sorry.

taylorotwell commented 10 years ago

We don't currently support limiting the selects on those relations because if it's not done properly it can break the query. You can remove the columns once the data has been retrieved if you like.

fmmajd commented 6 years ago

is it still an issue? or is there support for such things now?

websanova commented 6 years ago

Is there any way to set visible hidden properties on the relation directly then?

staudenmeir commented 6 years ago

This has been fixed in Laravel 5.7.6 (#25662).

lk77 commented 6 years ago

Hello,

https://github.com/laravel/framework/pull/25662 introduce a bug, we have thousand of queries using the with 'relation:field' syntax with polymorphic relations, and it's not working anymore, the relation is now empty. i don't know why, but it dont happen in 5.7.5, only until 5.7.6

work :

->with('morphTo');

don't work :

->with('morphTo:id,label');

if you have an idea, thanks.

acacha commented 5 years ago

ping to @staudenmeir

staudenmeir commented 5 years ago

@acacha Why?

lk77 commented 5 years ago

@acacha if the ping is because of my post, it has been resolved.

the precise syntax we were using was :

->with('morphTo:label');

without the id (contrary to what i said earlier)

Since 5.7.6, the select clause is applied, it was not the case in 5.7.5. It fails because of the missing id, and it breaks the app. It has been reworked and solved for us.