Skip to content

Instantly share code, notes, and snippets.

@whoan
Created December 2, 2016 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoan/421b1201013818aa902b50eea200dd55 to your computer and use it in GitHub Desktop.
Save whoan/421b1201013818aa902b50eea200dd55 to your computer and use it in GitHub Desktop.
Query constraints for an eager loading query
// suppose `brothers` has a user_id foreign key
class User extends Model
{
public function brothers() {
return $this->hasMany('App\Brother');
}
}
// bad way
return App\User::with(['brothers' => function($query) {
$query->select('name'); // if you forget user_id, the resultant collection will have empty arrays for `brothers`
}]);
// good way
return App\User::with(['brothers' => function($query) {
$query->select('name', 'user_id'); // could be this foreign key be selected automatically?
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment