简体   繁体   English

蛋糕PHP自定义查询

[英]cake php custom query

I have use custom query in cakephp but I dont understand how to run custom join query. 我在cakephp中使用了自定义查询,但是我不明白如何运行自定义联接查询。 I am using this code 我正在使用此代码

$arrayTemp1 = $this->User->query('SELECT DISTINCT
                u.id,u.hunting_association FROM ht_users as u LEFT JOIN 
                `ht_user_animal_prices` as uap ON uap.user_id=u.id  WHERE
                uap.animal_type_id='.$this->request->data['User']['animal'].' ');

User is the model for ht_users and UserAnimalPrice is the model for ht_user_animal_prices . User是模型ht_usersUserAnimalPrice是模型ht_user_animal_prices How to combine the query? 如何合并查询?

Please help. 请帮忙。

If you want to use custom queries and you want the data of UserAnimalPrice model, you just have to put the fields in the query. 如果要使用自定义查询,并且需要UserAnimalPrice模型的数据,则只需将字段放入查询中。 Something like: 就像是:

$arrayTemp1 = $this->User->query('SELECT DISTINCT u.id,u.hunting_association, uap.* FROM ht_users as u LEFT JOIN  ht_user_animal_prices as uap ON uap.user_id=u.id WHERE uap.animal_type_id='.$this->request->data['User']['animal'].' ');

If you prefer not to use custom queries: 如果您不想使用自定义查询:

$fields = array('User.id','User.hunting_association','UserAnimalPrice.*');
$join = array(
   array(
      'table' => 'ht_user_animal_prices',
      'alias' => 'UserAnimalPrice',
      'type'  => 'LEFT',
      'conditions' => array('UserAnimalPrice.user_id = User.id')
   )
);
$conditions = array('UserAnimalPrice.animal_type_id' => $this->request->data['User']['animal']);
$group = array('User.id');

arrayTemp1=arrayTemp1->find('all',array('fields'=>$fields,'joins'=>$join,'conditions'=>$conditions,'group'=>$group));

This is Correct Query u used .You can also use it in User Model like 这是您使用的正确查询。您也可以在用户模型中使用它,例如

public function getCustomUsersQuery()
{

$arrayTemp1 = $this->query("
    SELECT 
    DISTINCT u.id,u.hunting_association FROM ht_users as u 
    LEFT JOIN  
    ht_user_animal_prices as uap ON uap.user_id=u.id  
    WHERE 
    uap.animal_type_id='".$this->request->data['User']['animal']."'");
return $arrayTemp1; 
}

And call inside Users Controller 并在用户控制器内调用

$result = $this->getCustomUsersQuery();

Sorry I cannot comment on Rizwan answer. 抱歉,我无法评论Rizwan的答案。 If you received the "Call to a member function..." problem, make sure you have the following code 如果收到“调用成员函数...”的问题,请确保您具有以下代码

public $uses = array('User');

this tells that you want to access the user model in that controller. 这表明您要访问该控制器中的用户模型。 Then you will be allowed to do so. 然后,您将被允许这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM