LoginSignup
1
0

More than 3 years have passed since last update.

CakePHP3 ORマッパーでexists()を使用してデータの存在有無を確認

Last updated at Posted at 2019-06-17

サンプルコード

<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Sample Controller
 *
 *
 * @method \App\Model\Entity\Sample[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class SampleController extends AppController
{
    public function index()
    {
        // usersテーブルを読み込む
        $this->loadModel('Users');

        // idカラムが[1]の値のデータが存在するか確認
        $result = $this->Users
            ->find()
            ->exists(['id' => 1]);

        /*
         * 【返り値】
         * 存在する場合  => true
         * 存在しない場合 => false
         */
    }
}

※ORマッパーについては割愛する。

複数条件指定したい場合

  • exists()内の連想配列を「,」カンマ区切りで、繋げる。
<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Sample Controller
 *
 *
 * @method \App\Model\Entity\Sample[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class SampleController extends AppController
{
    public function index()
    {
        // usersテーブルを読み込む
        $this->loadModel('Users');

        // idカラムが[1]でかつ、nameカラムが['hoge']のデータが存在するか確認
        $result = $this->Users
            ->find()
            ->exists([
                'id' => 1,
                'name' => 'hoge'
            ]);

        /*
         * 【返り値】
         * 存在する場合  => true
         * 存在しない場合 => false
         */
    }
}
  • exists()と逆の動きをするnotExists()も存在する。
  • 【返り値】
    • 存在しない場合 => true
    • 存在する場合 => false

参考

SQLの場合

SELECT *
FROM table1
WHERE EXISTS
    ( SELECT id
     FROM table2
     WHERE table1.id = table2.hoge_id);

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0