您好,欢迎访问一九零五行业门户网

Cakephp查询关联表的方法总结

我们可以采用下列几种方式实现
{查询指定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方法
$data = $this->user->query($sql);
2.使用模型的bindmodel()和unbindmodel()方法
关于这两种方法的说明,请参照
http://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%'
以上就是cakephp查询关联表的方法总结的内容。
其它类似信息

推荐信息