在MAMP上運行的CakePHP 3.4。我有以下情形:CakePHP 3.4 - 如何在同一個查詢中添加2個內部連接?
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的書籤用教程(適用於我的情況下)。該邏輯將應該有一個產品有很多成分。烘烤後,這似乎工作正常。
我想達到的目標是:在特定產品的產品視圖上,我要顯示產品字段(與產品ID相關),以及成分。 用我的代碼,因爲它顯示產品字段(這是可以的),但只有joiner表ingredients_products的相關ID。
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
,但我無法找到任何東西,會讓我做這樣的查詢。 有誰知道這是如何實現的?
謝謝!
這個伎倆。謝謝!我已閱讀有關belongsToMany,但不知道如何在此示例上實現它。 – Tzi