2011-07-28 27 views
0

我最近开始尝试使用CakePHP。我在“普通”PHP中使用了这个查询,并且需要将它转换为CakePHP查找。但是,我似乎无法使它工作!cakephp中的子查询在其他表中查找

SELECT *, 
(SELECT name FROM `users` WHERE `users`.`id`=`products`.`creator`) AS creatorname 
FROM `products` 
WHERE `products`.`ID`='2' 

这是一个基本设置2表,用户和产品。每个产品都由用户创建,我需要加载用户的姓名以及产品信息。 (那么,为什么你需要的子查询我可以显示用户名,而不仅仅是用户ID。

有什么想法?

回答

2

如果您的关系设置正确:

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

保持得到'警告(512):SQL错误:1051:未知表'用户'[CORE/cake/libs/model/datasources/dbo_source.php,第684行]' – BloodPhilia

+0

明白了!谢谢! :D名称是错的... – BloodPhilia

1

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

反正做子查询的文档

阅读 Complex Find Conditions

好运

0

此外,公约注明外键应该是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') 
    ); 
} 
+0

我实际上使用列名虚假名称,但谢谢;) – BloodPhilia