Cake PHP 3.4 running on MAMP. I have the following scenario:
SQL tables
TABLE `Ingredients` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`category_id` int(11) NOT NULL,
`measure_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Table products
TABLE `Products` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`retail_price` float NOT NULL,
`best_before` int(11) NOT NULL,
`comments` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
TABLE `ingredients_products` (
`ingredient_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`qty` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Table models:
class IngredientsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('ingredients');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->hasMany('Purchases', [
'foreignKey' => 'ingredient_id'
]);
$this->hasMany('IngredientsProducts', [
'foreignKey' => 'ingredient_id'
]);
}
class ProductsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('products');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->hasMany('IngredientsProducts', [
'foreignKey' => 'product_id'
]);
}
On CakePHP, i followed the bookmarker tutorial of the cookbok (adapted to my scenario).The logic would be to have a product that has many ingredients. This seems to work fine after baking.
What i want to achieve is: on the product view for a specific product, I want to display the product fields (related to the id of the product), but also the ingredients. With my code as it is, I'm displaying the product fields (which is ok), but only the related ids of the joiner table ingredients_products.
public function view($id = null)
{
$product = $this->Products->get($id, [
'contain' => ['IngredientsProducts']
]);
$this->set('product', $product);
$this->set('_serialize', ['product']);
}
In SQL the query I would run is:
SELECT products.name as prod, ingredients.name as ingr, ingredients_products.qty as qty
FROM ingredients_products
INNER JOIN products
ON ingredients_products.product_id = products.id
INNER JOIN ingredients
ON ingredients_products.ingredient_id = Ingredients.id
I've been trying things I found on the Query builder page: https://book.cakephp.org/3.0/en/orm/query-builder.html
but I can't find anything that would let me do a query like that. Does anyone know how can this be achieved?
Thanks!