php - Laravel 5.1 loading relationship data into selected row -
i have timesheet
table , user
table in database. following relationship setup on timesheet
model.
/** * user owns timesheet. * * @return object */ public function user() { return $this->belongsto('app\models\user\user'); }
the above means can user data when select timesheets database using like:
$this->timesheet->wherestatus('approved')->with('user');
this load user object in result , if converted array so;
0 => array:13 [▼ "id" => 1 "user_id" => 2 "week" => 1 "year" => 2016 "week_ending" => "sunday 10th january 2016" "total_hours" => "45.00" "token" => "0e6796a2dc68066c8d36ff828c519af00657db02b733309b8a4ac0f7b5d6a385" "status" => "approved" "supervisor_id" => 1 "approved_by" => 1 "created_at" => "2016-01-13 15:42:49" "updated_at" => "2016-01-14 14:52:07" "user" => array:7 [▼ "id" => 2 "first_name" => "bill" "last_name" => "andrews" "email" => "bill.andrews@domain.com" "status" => 1 "created_at" => "2016-01-13 15:38:18" "updated_at" => "2016-01-14 14:50:03" ] ]
however, need first_name
, last_name
user table. there way merge/flatten user
array timesheet
looks instead;
0 => array:14 [▼ "id" => 1 "user_id" => 2 "week" => 1 "year" => 2016 "week_ending" => "sunday 10th january 2016" "total_hours" => "45.00" "token" => "0e6796a2dc68066c8d36ff828c519af00657db02b733309b8a4ac0f7b5d6a385" "status" => "approved" "supervisor_id" => 1 "approved_by" => 1 "created_at" => "2016-01-13 15:42:49" "updated_at" => "2016-01-14 14:52:07" "first_name" => "bill" "last_name" => "andrews" ]
i have tried use eager loading so;
$this->timesheet->with(['user' => function ($query) { $query->select('first_name', 'last_name'); }])->get()->toarray();
however, results in following output;
array:126 [▼ 0 => array:13 [▼ "id" => 1 "user_id" => 2 "week" => 1 "year" => 2016 "week_ending" => "sunday 10th january 2016" "total_hours" => "45.00" "token" => "0e6796a2dc68066c8d36ff828c519af00657db02b733309b8a4ac0f7b5d6a385" "status" => "approved" "supervisor_id" => 1 "approved_by" => 1 "created_at" => "2016-01-13 15:42:49" "updated_at" => "2016-01-14 14:52:07" "user" => null ]
the reason why user relationship null in second example because in order eloquent relationships work, needs keys tie relationships. in other words...
- get
timesheet
. - get
user
first_name
,last_name
. - build relationship.
- since did not fetch user's id,
user's id
,timesheet's user_id
not match relationship cannot built.
in order query work, need adjust this:
$this->timesheet->with(['user' => function ($query) { $query->select('id', 'first_name', 'last_name'); }])->get()->toarray();
with out of way, if want flattened result, think it's best use joins
rather eager loading because of nature of eager loading.
$this->timesheet ->join('users', 'timesheets.user_id', '=', 'users.id') ->select('timesheets.*', 'users.first_name', 'users.last_name') ->get()->toarray();
this assumes table names users
, timesheets
.
Comments
Post a Comment