I'm building an e-commerce site using CakePHP 2.3.x that has a Product
model associated with an Order
model in a HABTM relationship and I'm using orders_products
as my join table. I have all of the associations working correctly and doing a find()
on the Order
model brings up all the associated products. My problem is that I'm trying to make the association still happen if the Product
can't be found.
I'm saving relevant information in the association table but I can't find a way to make the association without the Product
model being found. I have info such as the item's name, price at time of sale, etc. stored in the association so the controller and view can compensate for an item that may have been deleted, changed ID somehow, or whatever else could happen.
I've searched all over but can't seem to find a better solution than manually building a query for the join table. Is there a proper Cake way of doing this, or should I use a separate model such as OrderProduct
?
Here's the Order
model:
class Order extends AppModel {
public $name = 'Order';
public $belongsTo = array('User');
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'orders_products',
'foreignKey' => 'order_id',
'associationForeignKey' => 'product_id',
'unique' => 'keepExisting'
)
);
}
And here's the Product
model:
class Product extends AppModel {
public $name = 'Product';
public $belongsTo = array('Category', 'Brand');
public $hasMany = array('ProductPhoto');
public $hasAndBelongsToMany = array(
'Order' => array(
'className' => 'Order',
'joinTable' => 'orders_products',
'foreignKey' => 'product_id',
'associationForeignKey' => 'order_id',
'unique' => 'keepExisting'
)
);
TLDR Version: When I do $this->Order->find('first', $options)
I get all the products in the returned Order
data, but only if there is a match on the join table (orders_products
) to the Product
model. I'm trying to make the join table result, $data['Order']['OrderProduct']
, in the returned data regardless if the Product
can be found in the database.