gpt4 book ai didi

mysql - CakePHP 3.x DB 映射,BelongsToMany 与 HasMany+HasOne

转载 作者:行者123 更新时间:2023-11-29 18:43:04 25 4
gpt4 key购买 nike

我在数据库中有三个表:(1) offers、(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',
]);

但是,由于可能出现空积,我应该使用 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',
]);

其中一种是正确的,还是还有第三种选择?

最佳答案

如果您需要检索连接表数据,无论产品是否存在/链接,那么您应该采用类似后一种解决方案。

但是,OfferRowsTable 类中的 Products 关联应该是 belongsTo 关联,因为 hasOne 需要外部键存在于目标表中,即 products 表中。使用 hasOne 最晚会在保存关联时破坏一些东西。

此外,ProductsTable 类中的 belongsToMany 关联应指向 Offers,而不是 OfferRows

关于mysql - CakePHP 3.x DB 映射,BelongsToMany 与 HasMany+HasOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44822157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com