LoginSignup
32
34

More than 5 years have passed since last update.

CakePHP3のbelongsToメモ

Last updated at Posted at 2015-11-09

リレーション絡みで調べたのでメモ

同一テーブル内の異なるカラムに同一テーブルへのリレーションをはる

日本語難しいね。要するに以下のようなテーブルの場合。
2つ以上のカラムがどっちもuserテーブルを指している場合。

テーブル
id
created_user_id
modified_user_id
TestTable.php
$this->belongsTo('CreatedUsers', [     // containで指定する名前
    'className' => 'Users',            // リレーション先のTable
    'foreignKey' => 'created_user_id', // FK
    'propertyName' => 'created_user',  // オブジェクトを入れるキー名
]);
$this->belongsTo('ModifiedUsers', [     // containで指定する名前
    'className' => 'Users',            // リレーション先のTable
    'foreignKey' => 'modified_user_id', // FK
    'propertyName' => 'modified_user',  // オブジェクトを入れるキー名
]);

ID以外でリレーションをはる

codeでリレーションを貼りたい場合。

テーブル
id
user_code
TestTable.php
$this->belongsTo('Users', [      // containで指定する名前
    'bindingKey' => 'code',      // リレーション先のカラム名
    'foreignKey' => 'user_code', // FK
]);

リレーション先のリレーションテーブルを持ってきたい

これも日本語難しい。
以下のテーブル構成でテーブルAからcompaniesテーブルを持ってきたい場合。

テーブルA
id
user_id
usersテーブル
id
company_id
companiesテーブル
id
TestController.php
$this->TableA->find('all')
    ->contain('Users', 'Users.Companies');
32
34
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
32
34