cakePHP 中的子查询在其他表中查找
我最近开始尝试 CakePHP。我在“普通”PHP 中使用了这个查询,需要将其转换为 CakePHP 查找。但我似乎无法让它发挥作用!
SELECT *,
(SELECT name FROM `users` WHERE `users`.`id`=`products`.`creator`) AS creatorname
FROM `products`
WHERE `products`.`ID`='2'
这是一个基本设置,包含 2 个表、用户和产品。每个产品都是由用户创建的,我需要加载用户名以及产品信息。 (所以我可以显示用户名而不仅仅是用户 ID。
有什么想法吗?
I recently started experimenting with CakePHP. I used this query in "normal" PHP and need to convert it to a CakePHP find. However I can't seem to make it work!
SELECT *,
(SELECT name FROM `users` WHERE `users`.`id`=`products`.`creator`) AS creatorname
FROM `products`
WHERE `products`.`ID`='2'
It's a basic set up with 2 tables, users and products. Every product gets created by a user and I need to load the name of the user along with the product info. (So I can display the username and not just the user id.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您已正确设置关系:
If you have the relations set up correctly:
为什么需要子查询?
无论如何,要进行子查询,请阅读文档中的 复杂查找条件
祝你好运
why do you need the subquery?
anyway to make subqueries read the Complex Find Conditions in the doc
Good Luck
此外,约定规定外键应该是
user_id
(而不是creator
),但是,如果您想保留该字段名称,您可以在关系中指定正确的字段,例如所以:Also, conventions state the foreign key should be
user_id
(rather thancreator
) but, if you want to keep that field name, your can specify the correct field in your relations like so: