cakePHP 中的子查询在其他表中查找

发布于 2024-11-27 04:27:31 字数 336 浏览 0 评论 0原文

我最近开始尝试 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

故事↓在人 2024-12-04 04:27:31

如果您已正确设置关系:

$this->Product->find(
    'first',
    array(
        'conditions' => array(
            'Product.id' => 2
        ),
        'fields' => array(
            'Product.*',
            'User.name'
        ),
        'recursive' => 1
    )
);

If you have the relations set up correctly:

$this->Product->find(
    'first',
    array(
        'conditions' => array(
            'Product.id' => 2
        ),
        'fields' => array(
            'Product.*',
            'User.name'
        ),
        'recursive' => 1
    )
);
困倦 2024-12-04 04:27:31

为什么需要子查询?

SELECT Product.*, User.name
FROM products as Product INNER JOIN users as User on (User.id = Product.creator)
WHERE Product.id = 2

无论如何,要进行子查询,请阅读文档中的 复杂查找条件

祝你好运

why do you need the subquery?

SELECT Product.*, User.name
FROM products as Product INNER JOIN users as User on (User.id = Product.creator)
WHERE Product.id = 2

anyway to make subqueries read the Complex Find Conditions in the doc

Good Luck

殤城〤 2024-12-04 04:27:31

此外,约定规定外键应该是 user_id (而不是 creator),但是,如果您想保留该字段名称,您可以在关系中指定正确的字段,例如所以:

class Product extends AppModel {
    public $belongsTo = array(
        'User' => array('foreign_key' => 'creator')
    );
}

class User extends AppModel {
    public $hasMany = array(
        'Product' => array('foreign_key' => 'creator')
    );
}

Also, conventions state the foreign key should be user_id (rather than creator) but, if you want to keep that field name, your can specify the correct field in your relations like so:

class Product extends AppModel {
    public $belongsTo = array(
        'User' => array('foreign_key' => 'creator')
    );
}

class User extends AppModel {
    public $hasMany = array(
        'Product' => array('foreign_key' => 'creator')
    );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文