Home > OS >  CakePHP 4 -> how to save join record
CakePHP 4 -> how to save join record

Time:07-04

I'm working on a CakePHP 4 application and I've set up a join table between Categories and Products called CategoriesProducts.

When I'm creating a new Product with a property called categories_products which contains an array like:

[
    [
        'category_id' => `x`
    ]
]

What's supposed to be saved into the join table is the category_id with the newly generated product_id.

The data isn't saved to the join table.

In the saveMany function I pass the:

[
    'associated' => [
        'Categories'
    ]
]

When I try to add associated => CategoriesProducts I get an error that the relationship is not defined.

Can someone explain to me how I can fill the join table? I've setup the database and baked the models with the CakePHP helper.

Thanks in advance!

CodePudding user response:

With the default association saving process you do not need to add data for join tables directly, instead you use the target association property and provide the primary keys of the records that you want to link.

So in your case that would probably be categories, eg your data for patching/creating an entity would be structured like this, where id is the primary key of the existing category that you want to associate to your new product:

[
    // ...
    'categories' => [
        [
            'id' => 123,
        ],
    ],
]

The ORM will then create the proper join table record automatically.

See also

  • Related