LoginSignup
36
49

More than 5 years have passed since last update.

CakePHP3リレーションまとめ

Posted at

CakePHP3でリレーションの定義を書くときに、どれを書いていいかわからなくなってきたと耳にしたので簡単にまとめてみます。

テーブル同士の繋がり(リレーション)は大きく分けて一対一・一対多・多対多の3種類があります。
これらに関してまとめていきます。

一対一

カラムが沢山あるテーブルを分解するときとかに使いますね。

1-1.png

UsersTable.php
// ユーザー詳細を1件持っているのでhasOne
$this->hasOne('UserDetails', [
    'foreignKey' => 'user_id',
]);
UserDetailsTable.php
// ユーザーに所属するものなのでbelongsTo
$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
]);

一対多

よく使うリレーションでね。一般的な親子関係のやつ。

1-N.png

ArticlesTable.php
// タグを沢山持っているのでhasMany
$this->hasMany('Tags', [
    'foreignKey' => 'tag_id',
]);
TagsTable.php
// 記事に所属するものなのでbelongsTo
$this->belongsTo('Articles', [
    'foreignKey' => 'article_id',
]);

多対多

ちょっと大きな設計になってくるとよく出現します。
同じタグは他の記事でも使いまわせるようにしたいとかの時。

1-N-1.png

ArticlesTable.php
// 中間テーブルをjoinTableに記載てbelongsToMany
$this->belongsToMany('Tags', [
    'joinTable' => 'ArticlesTags',
]);
TagsTable.php
// こっちも同じくbelongsToMany
$this->belongsToMany('Articles', [
    'joinTable' => 'ArticlesTags',
]);

belongsToManyが地味に楽ですね。
containで取得時も中間テーブルのレコードは省かれるので、不要な場合はこちらがいいかもしれないですね。

36
49
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
36
49