首頁 > php教程 > php手册 > 主體

Cakephp查詢關聯表的方法總結

黄舟
發布: 2016-12-20 09:35:07
原創
1872 人瀏覽過

我們可以採用下列幾種方式實作

{查詢指定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);
登入後複製

reee

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

rrreee

rrreee

rrreee
rrreee

rrreee也可以直接寫到find語句中,類似下面的

rrreee
注意事項:

🎜如果要查詢{User.name或Note.subject包含關鍵字keyword的所有記錄}🎜🎜此時,Cakephp的find方法無法實現這個查詢,必須使用上面介紹的自訂SQL語句,如下:🎜rrreee🎜 以上就是Cakephp查詢關聯表的方法總結的內容,更多相關內容請關注PHP中文網(m.sbmmt.com)! 🎜🎜🎜🎜🎜
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!