搜尋
首頁php教程php手册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);

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中文網(www.php.cn)! 🎜🎜🎜🎜🎜
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具