我在数据库中有三个表:(1)报价,(2)offer_rows,(3)产品。
offer_rows将始终指向要约,并且可能(但不总是)指向产品。 offer_rows还有其他字段,例如价格等。
与(My)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对产品引用没有不为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',
]);
是正确的还是第三种选择?
最佳答案
如果无论产品是否存在/已链接都需要检索联接表数据,则应采用后一种解决方案。
但是,由于Products
期望目标表(即OfferRowsTable
表)中存在外键,因此belongsTo
类中的hasOne
关联应为products
。保存关联时,最晚使用hasOne
会破坏事情。
同样,belongsToMany
类中的ProductsTable
关联应指向Offers
,而不是OfferRows
。
关于mysql - CakePHP 3.x DB映射,BelongsToMany与HasMany + HasOne,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44822157/