【发布时间】:2019-06-10 00:35:06
【问题描述】:
据我所知,“子查询可以为每条记录分配列值”。
示例:让我们考虑这个数据库,
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 eloquent?
更具体... 我有几张桌子,
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 循环来读取它们。
【问题讨论】:
-
为什么必须使用子查询?你熟悉Eloquent relationships吗?
-
感谢您的回复#Jonas。我想用 laravel 学习子查询并将它们应用于 4 到 5 个表连接。如果我使用关系比雄辩(据我所知)变得如此昂贵。这就是拖的原因。你能帮我联系吗?
-
好吧,更具体...让我们有一些表,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 ) 现在我想要一个查询来将每一行作为一个对象,并且数组查询应该返回结果 (transaction_id, session_name , from_account_name, to_account_name, action_name, another_table_detail, other_attributes) 最后将它们发送到 json,这样我就可以通过 for 循环读取它们。
-
您可以使用
selectSub()创建子查询。 -
非常感谢。我正在寻找这个。它适用于 selectSub()。