我在DB中有三个表:(1)提供,(2) offer_rows ,(3)产品。
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 对产品引用(当前没有)具有非空限制,则似乎应该使用 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',
]);
但是,如果有null产品的可能性,我应该使用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',
]);
其中一个是正确的还是第三个替代方案?
答案 0 :(得分:0)
如果您需要检索连接表数据而不管产品是否存在/是否已链接,那么您应该使用类似后一种解决方案。
但是Products
类中的OfferRowsTable
关联应该是belongsTo
,hasOne
期望外键存在于目标表中,即products
1}}表。最后使用hasOne
会在保存关联时解决问题。
此belongsToMany
课程中的ProductsTable
关联也应指向Offers
,而不是OfferRows
。