やったこと

webサービスを作るときに考えたことを垂れ流します

【CakePHP3】containによるデータ取得で主キー以外のバインド条件を指定!

CakePHP3でDBからレコードを検索するときに「contain」という命令がありますよね。

以下のような感じの命令です。

$authors = TableRegistry::get('Authors');
$records = $authors->find()->where(['Authors.author_id' => 1234])->contain(['Users']);


これを実行すると「Authors」テーブルの情報に加えて「Users」テーブルの情報も一緒に取得してくれるようになります。

「contain」を使うためには、「Authors」テーブルと「Users」テーブルに以下のような設定が必要です。

    //Authorsテーブル設定
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('authors');
        $this->displayField('author_id');
        $this->primaryKey('author_id');

        $this->hasOne('Users', [
            'joinType' => 'INNER',
            'foreignKey' => 'user_id',
            'bindingKey' => 'author_id'
        ]);
    }
    //Usersテーブル設定
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users');
        $this->displayField('user_id');
        $this->primaryKey('user_id');

        $this->hasOne('Authors', [
            'joinType' => 'INNER',
            'foreignKey' => 'author_id',
            'bindingKey' => ''user_id'
        ]);
    }

これで「Authors.author_id = Users.user_id」という条件で、Usersテーブルのレコードを引っ張ってきてくれます。

以上!