Cakephp 2.x where子句在多层次上

时间:2016-09-20 20:12:13

标签: cakephp

这是我的模特

MODEL USERLIST

class UserList extends AppModel {

public $belongsTo = array(
    'UserOwner' => array(
        'className' => 'Usermgmt.User',
        'foreignKey' => 'owner_id'
    ),
    'UserMember' => array(
        'className' => 'Usermgmt.User',
        'foreignKey' => 'member_id'
    )
);
public $recursive = -1;
public $actsAs = array('Containable');

模型用户

class User extends UserMgmtAppModel {

public $actsAs = array('Containable');

/**
 * This model belongs to following models
 *
 * @var array
 */
var $belongsTo = array('Usermgmt.UserGroup');

/**
 * This model has following models
 *
 * @var array
 */
var $hasMany = array(
    'LoginToken' => array('className' => 'Usermgmt.LoginToken', 'limit' => 1),
    'UserListOwner' => array('className' => 'UserList', 'foreignKey' => 'owner_id'),
    'UserListMember' => array('className' => 'UserList', 'foreignKey' => 'member_id'),
);
var $hasOne = array(
    'PhoneNumber' => array('className' => 'PhoneNumber', 'foreignKey' => 'user_id')
);

MODEL PHONENUMBER

class PhoneNumber extends AppModel {

public $belongsTo = array(
    'User' => array(
        'className' => 'Usermgmt.User'
    )
);

我想对多个级别的多个参数进行数据库请求。这是我的要求。

  $this->UserList->find("all", array('conditions' => array(
        "UserList.type" => 1,
        'UserList.owner_id' => $this->UserAuth->getUserId(),
        "UserMember.PhoneNumber.phoneNumber LIKE" => "%" . "514" . "%"
    ), 'fields'=>array('UserMember.first_name', 'UserMember.last_name', "PhoneNumber.phoneNumber")))

我的问题是当我运行此请求时,我总是收到一条SQL错误消息,指出UserMember.PhoneNumber.phoneNumber字段不存在。

我可以使用标准SQL来执行该请求,但我喜欢使用CakePhp。

我该怎么做?

感谢

1 个答案:

答案 0 :(得分:0)

您的专栏名称错误,此行"UserMember.PhoneNumber.phoneNumber LIKE" => "%" . "514" . "%"应该与您"PhoneNumber.phoneNumber LIKE" => "%" . "514" . "%"中的内容相似fields

您可能还需要指定要包含的模型: -

$this->UserList->find(
    'all', 
    array(
        'contain' => array(
            'UserMember' => array('PhoneNumber')
        ),
        'conditions' => array(
            'UserList.type' => 1,
            'UserList.owner_id' => $this->UserAuth->getUserId(),
            'PhoneNumber.phoneNumber LIKE' => '%' . '514' . '%'
        ), 
        'fields'=>array(
            'UserMember.first_name', 
            'UserMember.last_name', 
            'PhoneNumber.phoneNumber'
        )
    )
);