我們可以採用下列幾種方式實作
{查詢指定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);
reee
然後我們執行這個SQL語句,使用模型的query方法//重新绑定关联指定查询条件 $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);
2.使用模型的bindModel()和unbindModel()方法
http://api.cakephp.org/class/model
我們的做法是
class AppModel extends Model { //加载核心行为 var $actsAs = array('Containable'); }
3. 使用Cakephp的核心行為(Behavior) Containable
我們先建立自己的AppModel類別,建立檔案/app/app_model.php
$this->User->contain('Note.subject LIKE' => '%'.$keyword.'%'); $data = $this->User->find('all',array( 'conditions' => array( 'User.id' => $user_id ) ));
然後我們在控制器中,可以透過這樣的程式碼查詢
$data = $this->User->find('all',array( 'conditions' => array( 'User.id' => $user_id ), 'contain' => array( 'Note' => array( 'conditions' => array( 'Note.subject LIKE' => '%'.$keyword.'%' ) ) ) ));
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%'
rrreee
rrreeerrreee
rrreee
rrreee
注意事項: