CakePHPのアソシエーションのメモ。
制作者テーブル(makers)
makers |
---|
id |
name |
製品テーブル(products)
products |
---|
id |
name |
maker_id |
部品テーブル(parts)
parts |
---|
id |
name |
product_id |
Model/Product.phpで下記アソシエーションを定義する
<?php
App::uses( ‘AppModel’, ‘Model’ );
/**
* Product Model
*
* @property User $User
*/
class Product extends AppModel {
/**
* name
*
* @var
*/
public $name = 'Product';
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = [
'User' => [
'className' => 'Maker',
'foreignKey' => 'maker_id',
]
];
/**
* has many association
*
* @var array
*/
public $hasMany = [
'Container' => [
'className' => 'Part',
'dependent' => true, // --(1)
]
];
}
(1) hasManyの指定でdependentにtrueを設定していないとModelのdeleteメソッドでproductsのレコードを削除する処理でdeleteメソッドの第2引数がtrue(デフォルト)でも依存しているpartsテーブルの行は削除されない。
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。