CakePHP HABTM 关联规则
如果我想创建一个类别并能够通过标签将产品链接到它,我可以这样:
- 创建类别和产品 表。
- 创建一个标签表,其中包含以下标签: 红宝石、耳环、白金
- 创建一个
category_tags
并product_tags
表来映射它们 - 将类别和产品设置为 hasAndBelongsToMany 标签
- 将标签设置为 hasAndBelongsToMany 产品和 hasAndBelongsToMany 类别
现在假设我有 2 个产品,其中一个带有标签:Ruby 和 耳环,另一个带有标签:Ruby 和 手镯假设
我想创建一个红宝石耳环类别。
我可以将 Ruby 和 Earrings 标签添加到该类别中。但在正常的 HABTM 模型关联下,这两种产品都将被退回,因为尽管只有 1 个具有 earrings
标签,但它们都具有 ruby
标签。
如何使其仅匹配具有与该类别所有相同标签的产品(产品可以具有更多标签,但必须具有相应类别具有的所有标签)才能返回?
另外,更进一步,我如何将 -tags
添加到产品不得具有这些要返回的标签的类别中?
If I want to create a category and be able to link products to it by tags I can like so:
- Create the category and product
tables. - Create a tags table with tags like:
Ruby, Earrings, White-Gold - Create a
category_tags
andproduct_tags
table to map them - Set category and product to
hasAndBelongsToMany tags - Set tags to
hasAndBelongsToMany products and hasAndBelongsToMany categories
Now say I have 2 products one with tags: Ruby and Earrings and another with tags: Ruby and Bracelet
Say I want to create a Ruby Earrings category.
I could add the Ruby and Earrings tags to the category. But under normal HABTM Model associations both products will be returned because even though only 1 has an earrings
tag they both have a ruby
tag.
How can I make it only match products that have ALL of the same tags as the category (products can have more tags but must have all the tags the corresponding category has) in order be returned?
Also, taking that even further, how could I add -tags
to a category that the products must NOT have these tags to be returned?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面的脚本通过生成如下查询解决了我的问题:
PHP
SQL
但是我觉得这不是 CakePHP 的处理方式,我认为也许这应该在模型中处理,而不是在控制器中处理。但我不知道该怎么做。
The script below solved my issue by generating a query like so:
PHP
SQL
However I feel like this is not the way CakePHP is inteded to be treated, I think maybe this is something that should be handled in the model not in the controller. But I am not sure how to do that.