Created
December 2, 2016 07:50
-
-
Save whoan/421b1201013818aa902b50eea200dd55 to your computer and use it in GitHub Desktop.
Query constraints for an eager loading query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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