2017-06-29 11 views
0

Iは、DB内の3つのテーブルを有する:(1)を提供し、(2)offer_rows、(3)製品を。CakePHPのの3.x DBマッピング、hasManyの+ hasOneのVS BelongsToMany

offer_rows常に製品提供を指し、そしておそらく(常にではない)します。 offer_rows も有する等価格などの他のフィールド

(MY)SQLと同じ

:CakePHPの面で

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, 
    ... 
); 

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

いずれか正しいですか、または3番目の選択肢がありますか?

答えて

0

製品が存在するかリンクされているかにかかわらず結合テーブルのデータを取得する必要がある場合は、後者のソリューションのようなものを使用する必要があります。 hasOneproductsテーブルすなわち、ターゲットテーブルに存在する外部キーを期待するよう

しかしOfferRowsTableクラスのProducts関連は、belongsToものでなければなりません。 hasOneを使用すると、アソシエーションを保存するときに最新のことが壊れます。

また、ProductsTableクラスのbelongsToManyの関連付けは、Offersではなく、OfferRowsである必要があります。

関連する問題