Cakephp查询关联表的方法总结

291 阅读1分钟

我们可以采用下列几种方式实现

{查询指定User的Note中包含关键词keyword的所有信息}

1.SQL语句


SELECT * FROM Users AS User
LEFT JOIN Notes AS Note ON User.id = Note.user_id
WHERE
User.id = {$user_id}
AND
Note.subject LIKE '%{keyword}%'
然后我们执行这个SQL语句,使用模型的query方法

1
$data = $this->User->query($sql);
2.使用模型的bindModel()和unbindModel()方法

关于这两种方法的说明,请参照


api.cakephp.org/class/model

我们的做法是


//重新绑定关联指定查询条件

$this->User->unbindModel('Note');
$this->User->bindModel(
'hasMany' => array(
'Note' => array(
'conditions' => array(
'Note.subject LIKE' => '%'.$keyword.'%'
)
)
)
);

//指定主表条件获取数据
$data = $this->User->find('all',array(
'conditions' => array(
'User.id' => $user_id
)
));

//或者

$data = $this->User->read(null,$user_id);
3. 使用Cakephp的核心行为(Behavior) Containable

我们先建立自己的AppModel类,建立文件/app/app_model.php


class AppModel extends Model {

//加载核心行为
var $actsAs = array('Containable');

}
然后我们在控制器中,可以通过这样的代码查询


$this->User->contain('Note.subject LIKE' => '%'.$keyword.'%');

$data = $this->User->find('all',array(
'conditions' => array(
'User.id' => $user_id
)
));
也可以直接写到find语句中,类似下面的

?

$data = $this->User->find('all',array(
'conditions' => array(
'User.id' => $user_id
),
'contain' => array(
'Note' => array(
'conditions' => array(
'Note.subject LIKE' => '%'.$keyword.'%'
)
)
)
));


注意事项:

如果要查询{User.name或者Note.subject包含关键词keyword的所有记录}

此时,Cakephp的find方法无法实现这个查询,必须使用上面介绍的自定义SQL语句,如下:

?

SELECT *
FROM users AS User
LEFT JOIN notes AS Note ON User.id = Note.user_id
WHERE
User.name LIKE '%keyword%'
OR
Note.subject LIKE '%keyword%'