cakePHPで多対多のリレーションを使う機会があったので、その時のメモなどを。
多対多を説明するときには例によってブログの投稿(Item)とタグ(Tag)の関係が一番わかりやすいですね。
テーブル構成
テーブル構成が下記のようだったとします。
※実際はitemとtagはいろんなプロパティを持ってますが説明のために簡略化してます。
ソース
実際にリレーションでitemからtag、あるいはtagからitemを取得するときは下記のように取得します。
基本的にはItemとTagのモデルに多対多の設定を書けばOKです。
Item.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Item extends Model { public $hasAndBelongsToMany = [ 'Tag' => [ 'className' => 'tag', 'joinTable' => 'item_tags', 'foreignKey' => 'item_id', 'associationForeignKey' => 'tag_id', 'unique' => true ] ]; } |
Tag.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Tag extends Model { public $hasAndBelongsToMany = [ 'Item' => [ 'className' => 'item', 'joinTable' => 'item_tags', 'foreignKey' => 'tag_id', 'associationForeignKey' => 'item_id', 'unique' => true ] ]; } |
あとはControllerで普通にpaginateやfindメソッドを使用すれば、お互いのデータを紐付けて取得することができます。
リンク
hasAndBelongsToManyを活用して多対多のデータモデルを構築する方法
http://book.cakephp.org/2.0/ja/models/associations-linking-models-together.html