Cake PHP 3.4 работает на MAMP. У меня есть следующий сценарий:
SQL-таблицы
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;
Модели столов:
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'
]);
}
На CakePHP я следовал руководству по созданию закладок из cookbok (адаптированному к моему сценарию). Логика заключалась бы в том, чтобы иметь продукт, который состоит из многих ингредиентов. Это, кажется, работает нормально после выпечки.
Чего я хочу добиться, так это: в представлении продукта для конкретного продукта я хочу отображать поля продукта (связанные с идентификатором продукта), а также ингредиенты. С моим кодом, как есть, я показываю поля продукта (что нормально), но только связанные идентификаторы столярной таблицы ингредиенты_продукты.
public function view($id = null)
{
$product = $this->Products->get($id, [
'contain' => ['IngredientsProducts']
]);
$this->set('product', $product);
$this->set('_serialize', ['product']);
}
В SQL запрос, который я бы выполнил:
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
Я пробовал то, что нашел на странице конструктора запросов: https://book.cakephp.org/3.0/en/orm/query-builder.html
но я не могу найти ничего, что позволило бы мне сделать такой запрос. Кто-нибудь знает, как этого можно достичь?
Спасибо!