luk luk - 1 month ago 22
PHP Question

laravel 4.2 eloquent: get all() + related column

Let's say we have 2 models, with following relations:

Users:

public function BookCode() {
return $this->hasOne( 'BookCode' );
}


BookCode:

public function User() {
return $this->belongsTo( 'User' );
}


Now we'd like to get all records from User with book_code from BookCode (empty if none) as an array. Is something like that possible? The only thing I came up, which seems to be very slow (takes 30 secs to execute), was:

$users = User::all();

foreach( $users as $user ) {
$users_array[] = array(
$user->first_name,
$user->last_name,

// this is very slow
$user->BookCode['book_code'],
$user->created_at,
$user->updated_at,
);
}


Would it be possible to get an array of Users with related book_codes "in one go"? Couldn't find any solution to this for 5 hrs now.

Answer

Set the relationships that should be eager loaded.

$users = User::with('BookCode')->get();
Comments