开发者

Subquery in cakePHP to lookup in other table

开发者 https://www.devze.com 2023-03-23 08:28 出处:网络
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!

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`=`pro开发者_如何学编程ducts`.`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?


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
    )
);


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


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')
    );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消