I have 3 tables
- producttypes (id, name); The table is filled with values “Product” and “Ingredient”
- products (id, name, producttype_id)
- ingredients_products (id, ingredient_id, product_id) (ingredient_id comes from table products, product_id comes from table products)
A Product can be “Product” or “Ingredient”.
I want to get a belongstomany Relation on Products, where a product belongstomany products.
In ProductsTable i added:
$this->belongsToMany('IngredientsProducts', [ 'joinTable' => 'ingredients_products', 'foreignKey' => 'product_id', 'targetForeignKey' => 'ingredient_id'
In entity products i added:
‘ingredientsproducts’=>true,`
In ProductsController I select the ingredients:
$ingredients=$this->Products->find(‘list’,[
‘conditions’=>[‘Products.salespoint_id’=>$this->request->getSession()->read(‘salespoint_id’),‘Products.producttype_id’=>2],
]);
In add Form i have:
echo $this->Form->control(‘ingredientsproducts._ids’, [‘options’ => $ingredients,‘type’=>‘select’,‘multiple’=>‘checkbox’,‘hiddenField’=>false,‘label’=>false]);
After submitting the form I get this request->data
[
'name' => 'Product with ingredient',
'ordernumber' => '',
'description' => '',
'productcategory_id' => '',
'gtin' => '',
'allergens' => [
'_ids' => [
(int) 0 => '1',
(int) 1 => '2',
],
],
'ingredientsproducts' => [
'_ids' => [
(int) 0 => '2',
],
],
'image_file' => object(Laminas\Diactoros\UploadedFile) id:0 { },
]
After patching, the entity looks like this (I show only the relevant parts; hasErrors is false):
'allergens' => [
(int) 0 => object(App\Model\Entity\Allergen) id:1 { },
(int) 1 => object(App\Model\Entity\Allergen) id:4 { },
]
'ingredientsproducts' => [
'_ids' => [
(int) 0 => '2',
],
So it seems, that I something completely did not understood on associating table together.
Can someone maybe help me to associate the table products with itself?
If more information is needed, please let me know.