2017-06-29 93 views
0

我在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', 
]); 

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

回答

0

如果您需要检索连接表数据而不管产品是否存在/被链接,那么您应该使用类似于后者的解决方案。

然而Products协会在OfferRowsTable类应该是一个belongsTo之一,hasOne预计外键到目标表中存在,即products表。最近使用hasOne时会保存关联。

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