Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yii's MANY_MANY implementation has limitations which might be addressed in later Yii version.</p> <p>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:</p> <pre><code>public function relations() { return array( 'cartProducts'=&gt;array(self::HAS_MANY, 'CartProduct', 'cart_id'), 'products'=&gt;array(self::HAS_MANY, 'Product', 'product_id', 'through' =&gt; 'CartProduct'), ); } </code></pre> <p>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".</p> <p>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):</p> <pre><code>public function relations() { return array( 'products'=&gt;array(self::MANY_MANY, 'Product', 'cart_products(cart_id, product_id)'), 'productsAmount'=&gt;array(self::STAT, 'Product', 'cart_products(cart_id, product_id)'), ); } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload