我目前有这段代码:
return Datatable::query($query = DB::table('acquisitions')
->where('acquisitions.deleted_at', '=', null)
->where('acquisitions.status', '!=', 2)
->join('contacts', 'acquisitions.contact_id', '=', 'contacts.id')
->join('user', 'acquisitions.user_id', '=', 'user.id')
->select('contacts.*', 'acquisitions.*', 'acquisitions.id as acquisitions_id', 'user.first_name as supervisor_first_name', 'user.last_name as supervisor_last_name', 'user.id as user_id'))
来自用户表的数据用于2列:acquisitions.supervisor_id
和acquisitions.user_id
。我需要这两个表的first_name
和last_name
,但上述查询目前只使用id
字段中的acquisitions.user_id
。我也尝试使用表别名,这也行不通,我假设我在这里做错了。
简而言之:我还需要查询根据acquisitions.supervisor_id
中的ID为用户选择数据,并将其设为supervisor_first_name
和supervisor_last_name
。
答案 0 :(得分:1)
根据您对其他答案的最后评论,您需要每个参考表自我加入。试试这个:
$result = DB::select('SELECT
u.name user_first_name,
u.last_name user_last_name,
u.email user_email,
s.name supervisor_name,
s.last_name supervisor_last_name,
s.email supervisor_email
FROM acquisitions a
JOIN users u ON a.user_id = u.id
JOIN users s ON a.supervisor_id = s.id');
return $result;
请注意$result
是StdClass
个对象的数组,而不是Collection,但您仍然可以迭代它并调用当前项的值:
foreach ($result as $item) {
print($item->supervisor_first_name);
}
如果您需要WHERE
条款,例如要从acquisitions
获取特定用户的行,您可以通过向查询添加参数来执行此操作,如下所示:
$result = DB::select('SELECT
u.name user_first_name,
u.last_name user_last_name,
u.email user_email,
s.name supervisor_name,
s.last_name supervisor_last_name,
s.email supervisor_email
FROM acquisitions a
JOIN users u ON a.user_id = u.id
JOIN users s ON a.supervisor_id = s.id
WHERE a.user_id = ?
', [3]);
修改强>
如果您需要将结果集设为Collection
,则可以使用hydrate
方法轻松将数组转换为1:
$userdata = \App\User::hydrate($result); // $userdata is now a collection of models
答案 1 :(得分:0)
应该是这样的;
return Datatable::query($query = DB::table('acquisitions')
->where('acquisitions.deleted_at', '=', null)
->where('acquisitions.status', '!=', 2)
->join('contacts', 'acquisitions.contact_id', '=', 'contacts.id')
->join('user', 'acquisitions.user_id', '=', 'user.id')
->select( \DB::raw(" contacts.*, acquisitions.*, acquisitions.id as acquisitions_id, user.first_name as supervisor_first_name, user.last_name as supervisor_last_name, user.id as user_id ") )
);
答案 2 :(得分:0)
$devices = DB::table('devices as d')
->leftJoin('users as au', 'd.assigned_user_id', '=', 'au.id')
->leftJoin('users as cu', 'd.completed_by_user_id', '=', 'cu.id')
->select('d.id','au.name as assigned_user_name','cu.name as completed_by_user_name');
也请点击此链接