Laravel 2-in-1 quick tip about hasMany relationships.
Let's imagine that you have this Model method:
app/Models/City.php:
class City extends Model { public function restaurants() { return $this->hasMany(Restaurant::class); }}
Then you may load cities with all their restaurants, like this:
City::with('restaurants')->get();
But what if you don't want to load ALL the fields of the restaurant, to save some memory and bandwidth? You can do this:
City::with('restaurants:id,city_id,name')->get();
But be careful. If you skip the RELATIONSHIP column, it will not give you the data at all:
City::with('restaurants:id,name')->get();
This will return NO restaurants.
The last 2 queries are the same, probably a mistake ? anyways, thanks for this great site :)
Thanks, well noticed! Fixed now, was writing this thing in a rush, just wanted to save my tweet in a blog format so it would be searchable in the future :)