同じモデルをHABTMプラスwithする
HABTM(ハビタム、hasAndBelongsToMany)とは、モデル間の中間テーブルによる多対多のリレーションを構築します。
料理モデル「Cooking」と素材モデル「Food」がある場合、「cooking_id」「food_id」のフィールドを持つ中間テーブル「cookings_foods」テーブルを作り、モデル「Cooking」には、
var $hasAndBelongsToMany = array('Food');
と記述するとCooking->findで自動的にFoodをぞろぞろ取ってきてくれる、、、はずです。すいません、この例は未検証です。
この場合、取得できるのはCookingとFoodだけですが、「with」句を付けると「CookingsFood」もついでに取ってきてくれます。
var $hasAndBelongsToMany = array('Food' =>
array('with' => 'CookingsFood')
);
中間テーブルには「承認済」とか「仲良し度」とかの関係性を記録したい場合に使えます。
今回はこれに加えて、同一テーブル間を多対多でつなぎたいと考えました。例はSNSのユーザー間でマイミクをするようなものです。
ユーザー「Account」モデルと、「account_id」「member_id」を持つ中間「Member」モデルを用意します。
Accountモデルに、
var $hasAndBelongsToMany = array(
'Friend' => array('className' => 'Account',
'joinTable' => 'members',
'with' => 'Member',
'foreignKey' => 'account_id',
'associationForeignKey' => 'member_id',
'conditions' => '',
'order' => '',
'limit' => '',
'uniq' => false,
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
を記述します。お友達は「Friend」の下に、その中の「Member」にmemberモデルの内容が収められます。

