我在DB三個表:(1)提供,(2)offer_rows,(3)產品。CakePHP的3.X DB映射,BelongsToMany VS的hasMany + HasOne
offer_rows總是指向一個報價,以及可能(但不總是)與產品。 offer_rows也具有其它字段,諸如價格等
同樣的,(我)SQL:
create table offers(
id serial not null auto_increment primary key,
...
);
create table offer_rows(
id serial not null auto_increment primary key,
product_id bigint(20) unsigned references products(id),
offer_id bigint(20) unsigned not null references offers(id),
price decimal(15,2),
...
);
create table products(
id serial not null auto_increment primary key,
...
);
在CakePHP的術語(3.3.16),與任選參考的產物,什麼是正確的映射?
如果offer_rows有一個NOT NULL限制產品的參考(它目前沒有),這似乎是一個BelongsToMany應使用:
(class OffersTable)
@property \Cake\ORM\Association\BelongsToMany $Products
// initialize
$this->belongsToMany('Products', [
'through' => 'OfferRows',
'foreignKey' => 'offer_id',
'joinType' => 'INNER',
'joinTable' => 'offer_rows',
]);
(class OfferRowsTable)
@property \Cake\ORM\Association\BelongsTo $Products
@property \Cake\ORM\Association\BelongsTo $Offers
// initialize
$this->belongsTo('Products', [
'foreignKey' => 'product_id'
]);
$this->belongsTo('Offers', [
'foreignKey' => 'offer_id',
'joinType' => 'INNER'
]);
(class ProductsTable)
@property \Cake\ORM\Association\BelongsToMany $Offers
// initialize
$this->belongsToMany('Offers', [
'through' => 'OfferRows',
'foreignKey' => 'product_id',
'joinType' => 'INNER',
'joinTable' => 'offer_rows',
]);
然而,隨着可能性的空產品,我應該使用HasMany + HasOne來代替嗎?
(class OffersTable)
@property \Cake\ORM\Association\HasMany $OfferRows
// initialize
$this->hasMany('OfferRows', [
'foreignKey' => 'offer_id'
]);
(class OfferRowsTable)
@property \Cake\ORM\Association\BelongsTo $Offers
@property \Cake\ORM\Association\HasOne $Products
// initialize
$this->belongsTo('Offers', [
'foreignKey' => 'offer_id',
'joinType' => 'INNER'
]);
$this->hasOne('Products', [
'className' => 'Products',
'propertyName' => 'reference_product_obj',
'foreignKey' => 'reference_product'
]);
(class ProductsTable)
@property \Cake\ORM\Association\BelongsToMany $OfferRows
// initialize
$this->belongsToMany('OfferRows', [
'foreignKey' => 'product_id',
'joinType' => 'INNER',
]);
是一個正確的,還是有第三種選擇?