EAGER LOADING POLYMORPHIC RELATIONSHIPS
Feb 02, 2024 Copy Link
In case you're retrieving a huge data it's so IMPORTANT to indicate which columns exactly you need. For instance, if you want to get the phone details with its creator, you should use Eager Loading and select the columns ONLY that you need for more optimization:
Phone::with(['user:name'])->get();
The previous code will throw an exception because Laravel when joining both tables will not find the `user_id`
so, we should get both the `id`
and `name`
columns. But, what if you wanna retrieve data with Polymorphic Relationships
?
You can say that you will do the same thing:
Phone::with(['image:imageable_id,name'])->get();
The former code will throw an exception also that's because Laravel needs the `imageable_type`
column to match its value with the proper model class
We can that
It does not matter the columns you select whenever you get the columns that are required in the join operations.