据我所知,“子查询可以为每个记录分配列值”。
示例:让我们考虑这个数据库,
user (id, name, age)
user_detail (user_id[foreign], user_email, address)
现在我们可以通过子查询选择所有电子邮件和名称,如下所示:
SELECT id, (SELECT user_email FROM user_detail WHERE user_detail.user_id = user.id LIMIT 1) as email,
name, age
FROM user
WHERE 1
输出表如下:
_ _ _ _ _ _ _ _ _ _ _ _ _
| id | email | name | age |
+-------------------------+
---------All rows----------
现在我该如何用laravel雄辩地查询?
更具体... 我有一些桌子,
1. session (id, name)
2. account (id, name, group)
3. action (id, action_name, detail)
4. another_table (id, detail)
5. transaction (id, from_account_id, to_account_id, session_id,
action_table_id, another_table_id, other_attributes )
现在我想要一个查询来将每一行作为一个对象,并打孔一个数组 查询应返回
result (transaction_id, session_name, from_account_name, to_account_name,
action_name, another_table_detail, other_attributes)
最后将它们发送到json,这样我就可以通过for循环读取它们。
答案 0 :(得分:0)
尝试一下
$users = User::join('users', 'users.id', '=', 'user_detail')->get();
应将两个表与所需的所有记录连接起来。
答案 1 :(得分:0)
感谢Jonas-staudenmeir.他帮助我找到了解决方法。
在这种情况下,我们可以使用laravel查询构建器类中的selectSub()
方法。 selectSub()
对于第一个:
$user_email = DB::table('user_detail')
->select('user_detail.user_email')
->whereRaw('user_detail.user_id = user.id')
->take(1);
$data = DB::table('user')
->select('name', 'age')
->selectSub($user_email, 'email') // selectSub(sub_query, as)
->get();
第二个:
//session query
$session = DB::table('session')
->select('session.name')
->whereRaw('transaction.session_id = session.id')
->take(1);
//from_account query
$from_account = DB::table('account')
->select('account.name')
->whereRaw('transaction.from_account_id = account.id')
->take(1);
//to_account query
$to_account = DB::table('account')
->select('account.name')
->whereRaw('transaction.to_account_id = account.id')
->take(1);
//action query
$action = DB::table('action')
->select('action.action_name')
->whereRaw('transaction.action_table_id = action.id')
->take(1);
//another_table query
$another_table = DB::table('another_table')
->select('another_table.detail')
->whereRaw('transaction.another_table_id = another_table.id')
->take(1);
$data = DB::table('transaction')
->select('transaction.id as transaction_id', 'other_attributes')
->selectSub($session, 'session_name') //session as session_name
->selectSub($from_account, 'from_account_name') //from_account as from_account_name
->selectSub($to_account, 'session_name') //to_account as to_account_name
->selectSub($action, 'action_name') //action as action_name
->selectSub($another_table, 'another_table_detail') //another_table as another_table_detail
->get();
尽管我们可以使用联接或左联接。哪个查询更快取决于数据,索引,相关性,数据量,查询等。子查询的速度可能比LEFT [OUTER] JOINS慢,但在我看来,它们的优势是可读性稍高。 join-vs-sub-query