[Yii] [SQL]连接表时不获取记录以获取商品数量

时间:2014-06-14 08:06:05

标签: activerecord yii

我有以下代码可以按优惠(出价和购买)排序:

$clean_criteria = new CDbCriteria;
$clean_criteria->order = 'promoted DESC'; 

$criteria = new CDbCriteria;
$criteria->order = 'promoted DESC';
$criteria->select = "*, (COUNT(aa.id) + COUNT(ab.id)) as offers";
$criteria->join = ' LEFT JOIN auction_bid aa ON (t.id = aa.auction)';
$criteria->join .= ' LEFT JOIN auction_buy ab ON (t.id = ab.auction)';

我正在使用分页和排序:

$item_count = Auction::model()->count($clean_criteria);
$pages = new CPagination($item_count);
$pages->setPageSize(5);
$pages->applyLimit($clean_criteria); 

$sort = new CSort('Auction');
$sort->attributes = array('offers'=>array('asc'=>'offers', 'desc'=>'offers DESC'));
$sort->applyOrder($clean_criteria);

但要获得优惠,我必须在寻找拍卖时使用$crtieria

$auctions = Auction::model()->findAll($criteria);

在网站上有正确的页数,但每次都有相同的拍卖。问题是查询只返回一条记录,但如何解决这个问题?

P.s也许我使用了错误的联合类型,没有报价的拍卖会被退回?

修改

此代码正常运行:

$criteria->select = "*, COUNT(abid.id) AS offers1";
$criteria->join = ' LEFT JOIN auction_bid abid ON (t.id = abid.auction)';
$criteria->group = 't.id';

首次拍卖会返回offers1 = 1

也是如此:

$criteria->select = "*, COUNT(abuy.id) AS offers2";
$criteria->join = ' LEFT JOIN auction_buy abuy ON (t.id = abuy.auction)';
$criteria->group = 't.id';

首次拍卖会返回offers2 = 4

但是当我把它组合成一个查询时:

$criteria->select = "*, COUNT(abid.id) AS offers1, COUNT(abuy.id) AS offers2";
$criteria->join = ' LEFT JOIN auction_bid abid ON (t.id = abid.auction)';
$criteria->join .= ' LEFT JOIN auction_buy abuy ON (t.id = abuy.auction)';
$criteria->group = 't.id';

首次拍卖会返回offers1 = 4 and offers2 = 4

如何解决?

1 个答案:

答案 0 :(得分:0)

<强>解决:

标准:

$criteria->select = "*, (COUNT(DISTINCT abid.id) + COUNT(DISTINCT abuy.quantity)) AS `offers`";
$criteria->join = ' LEFT JOIN auction_bid abid ON (t.id = abid.auction)';
$criteria->join .= ' LEFT JOIN auction_buy abuy ON (t.id = abuy.auction)';
$criteria->group = 't.id';

分选

$sort = new CSort('Auction');
$sort->attributes = array('offers');
$sort->applyOrder($criteria);

分页:

$item_count = Auction::model()->count($clean_criteria);
$pages = new CPagination($item_count);
$pages->applyLimit($criteria);  

搜索:

$auctions = Auction::model()->findAll($criteria);