CAKEPHP 4->如何保存加入记录

发布于 2025-02-11 20:52:59 字数 544 浏览 2 评论 0 原文

我正在处理CakePHP 4应用程序,并且我已经在类别产品 properts categoriesproducts 之间设置了一个加入表。

当我使用名为 categories_products 的属性创建新产品时,其中包含一个类似的数组:

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

应该保存在JOIN表中的是 category_id ,新生成的 代码> product_id 。

数据未保存到联接表。

在Savemany功能中,我通过:

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

尝试添加关联=>类别生产我会发现该关系未定义的错误。

有人可以向我解释如何填充加入表吗?我已经设置了数据库,并用CakePHP助手烘烤模型。

提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瑾夏年华 2025-02-18 20:52:59

借助默认关联保存过程,您无需直接添加数据以直接添加数据,而是使用目标关联属性并提供要链接的记录的主要键。

因此,在您的情况下,可能是类别,例如用于修补/创建实体的数据将是这样的,其中 id 是现有类别的主要键您想与您的新产品相关联:

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

ORM将自动创建正确的加入表记录。

另请参见

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文