2017-06-29 78 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