我的数据库中有一个timesheet
表和一个user
表。以下关系是在 timesheet
模型上设置的。
/**
* The user that owns the timesheet.
*
* @return Object
*/
public function user()
{
return $this->belongsTo('App\Models\User\User');
}
上面的意思是当我从数据库中选择时间表时,我可以通过使用类似的东西来获取用户数据:
$this->timesheet->whereStatus('Approved')->with('user');
这将在结果中加载用户对象,如果转换为数组将如下所示;
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"
]
]
但是,我只需要用户表中的first_name
和last_name
。有没有一种方法可以将 user
数组与 timesheet
合并/展平,使其看起来像这样;
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"
]
我试过像这样使用预加载;
$this->timesheet->with(['user' => function ($query) {
$query->select('first_name', 'last_name');
}])->get()->toArray();
但是,它会产生以下输出;
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
]
最佳答案
第二个示例中用户关系为空的原因是,为了使 Eloquent 关系起作用,它需要绑定(bind)关系的键。换句话说……
- 获取
时间表
。 - 仅使用
first_name
和last_name
获取user
。 - 建立关系。
- 由于您没有获取用户 ID,因此
user's id
和timesheet's user_id
不匹配,因此无法建立关系。
为了使您的查询有效,您需要像这样调整它:
$this->timesheet->with(['user' => function ($query) {
$query->select('id', 'first_name', 'last_name');
}])->get()->toArray();
除此之外,如果您想要扁平化的结果,我认为最好使用 joins
而不是预先加载,因为预先加载的性质。
$this->timesheet
->join('users', 'timesheets.user_id', '=', 'users.id')
->select('timesheets.*', 'users.first_name', 'users.last_name')
->get()->toArray();
这假设您的表名称是 users
和 timesheets
。
关于php - Laravel 5.1 将关系数据加载到选定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35271896/