开发者

How to avoid duplicate products with Product hasOne Offer?

I have two models Products and Offers开发者_开发百科. Products hasOne Offer. Models are binded with

//Product model:
hasOne
  Offer
     foreignKey => false
     conditions => array(Product.productnumber = Offer.productnumber) // Just normal fields

//Offer model:
belongsTo
    Product

There can be many offers with same Offer.productnumber and different Offer.price. What I want to do is find all products so that there is only one offer present with cheapest Offer.price. But now when I trying to do that I get as many duplicate Products as there is Offers with same productnumber. How to avoid this?

I have also seen this: hasMany reduced to hasOne in CakePHP But no luck with containable.

Is only (easiest) option to get separate arrays and then combine them "manually"?


Product hasMany Offers. Product hasMany LowestOffer with an order clause in the relationship conditions array sorted on price ASC and a limit=>1 clause.

Then do a find with containable and pull the LowestOffer back when you want just the single cheapest offer or pull back Offers when you want them all.


If you want Many offers to one product, then you've to use hasMany. product hasMany offers.

That's the way you should model the relationship in your models. I mean, think about it, if you have one book in your store, and it can have only one offer, that makes no sense.

Ok, now, to get all the books that have just 1 offer, i just can think something like this:

SELECT p.id FROM products p JOIN offers o ON(p.id=o.product_id) WHERE p.id IN (
   SELECT oo.product_id FROM offers oo GROUP BY oo.product_id WHERE SUM(oo.product_id)=1
)

Try to put that in Model::find() syntax, or just use the Model::query() method.

EDIT:

If you want the offer with the bigger price.

SELECT p.id FROM products p JOIN offers o ON(p.id=o.product_id) WHERE p.id IN (
   SELECT oo.product_id FROM offers oo GROUP BY oo.product_id WHERE OO.id = MAX(oo.price)
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜