ホームページ  >  記事  >  php教程  >  Cakephp で関連テーブルをクエリする方法のまとめ

Cakephp で関連テーブルをクエリする方法のまとめ

黄舟
黄舟オリジナル
2016-12-20 09:35:071968ブラウズ

以下の方法で実装できます

{指定したユーザーのメモにあるキーワードキーワードを含む情報を全てクエリする}

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文を実行し、モデル

$data = $this->User->query($sql);

2. モデルのbindModel() メソッドと unbindModel() メソッドを使用します

これら 2 つのメソッドの手順については、こちらを参照してください


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 にキーワード キーワードが含まれるすべてのレコード} をクエリしたい場合

, 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 が関連するテーブルをクエリする方法の概要です。その他の関連コンテンツについては、PHP 中国語 Web サイト ( www.php.cn)!


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。