多对多,还有另一列
我想知道是否有人遇到过这个问题。
假设我有两个表:产品和购物车(多对多相关)。
现在,连接表有附加列 - 数量(购物车中有多少特定类型的产品)。
我的问题是我无法通过以下关系访问“金额”列:
public function relations() { return array( 'products'=>array(self::MANY_MANY, 'Product', 'cart_products(cart_id, product_id)'), ); }
我也尝试过:
'products'=>array(self::HAS_MANY, 'Product','product_id','through'=>'cart_products'),
但没有运气。
I'm wondering if anyone has faced this issue.
Let's assume I have two tables: products and carts (related many to many).
Now, joining table has additional column - amount (how many products of particular type is in the cart).
My problem is that I cannot access "amount" column via following relation:
public function relations() { return array( 'products'=>array(self::MANY_MANY, 'Product', 'cart_products(cart_id, product_id)'), ); }
I also tried:
'products'=>array(self::HAS_MANY, 'Product','product_id','through'=>'cart_products'),
with no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Yii 的 MANY_MANY 实现有一些限制,这些限制可能会在以后的 Yii 版本中得到解决。
解决方案是为 MANY_MANY 表再使用一个模型类。例如,创建 AR 类 CartProduct,然后您的购物车的关系将变为:
这样您将可以在 Cart 实例的 cartProducts 魔法公共属性中引用 CartProducts 模型,并且能够更新您的“金额”。
现在是我说我不喜欢你解决问题的方法的好时机 - 有“金额”列来保存购物车中的产品数量,因为你必须保留两个事实(映射的产品的实际数量)到数据库中的购物车和相关表中的计数器缓存“金额”字段”)。除非您有非常非常繁重的应用程序需要此数据库非规范化,否则我会执行“计数器关系”来获取产品计数,而不是将该值缓存在列中,例如(将以下关系添加到您的购物车模型):
这样,您可以调用 cart->protuctsAmount 属性,它将通过简单而快速的计数查询(我认为将被缓存)返回实际金额,而不是依赖每次更改购物车产品时,都必须通过代码或数据库触发器重新生成缓存值。
Yii's MANY_MANY implementation has limitations which might be addressed in later Yii version.
The solution to this is to use one more model class for the MANY_MANY table. For example create AR class CartProduct and then the relation for your cart would become:
This way you will have reference to CartProducts model in the cartProducts magic public property of the Cart instance and will be able to update your "amount".
Now its good time that I say that I do not like your approach to the problem - having "amount" column that holds the count of the products in the cart, because you have to keep two truths (the actual amount of products that are mapped to the cart in the db and the counter cache "amount" field in the relating table"). Inless you have very very heavy application that needs this db denormalization, I would do a "counter relation" to get the products count, instead of caching that value in column, like this (add the following relation to your Cart model):
This way, you can call the cart->protuctsAmount property and it will return the actual amount with a simple and fast count query (which will be cached I think) instead of relying on cached value that have to be regenerated by your code or by db triggers every time you change the cart products.