在yii ActiveRecord中使用左连接嵌套选择

时间:2014-04-24 08:17:07

标签: php mysql yii

我有一些桌子。主表为contractors,并且具有链接表address,其中存在某种类型的地址(1, 2, 3)。在执行LEFT JOIN ORDER BY type时需要,因为在某些情况下,可以使用1和2或3类型的地址,但有时地址在字段type中不连续。 我提出了满足我要求的请求,但无法在ActiveRecord中创建相同的查询。

所以直接在数据库中的请求如下所示:

SELECT t.id, addresses.address FROM contractor as t
    LEFT JOIN (SELECT * FROM address ORDER BY address.type) as addresses 
    ON addresses.address != '' AND addresses.contractor_id = t.id
    WHERE ((t.type='store') AND (t.name LIKE '%name%' OR addresses.address LIKE '%name%'))
    GROUP BY t.id

在模型关系中,现在看起来:

public function relations(){
  'addresses' => array(
      self::HAS_MANY,
      'Address',
      'contractor_id',
      'on' => "addresses.address != ''",
      'order' => 'addresses.type ASC'
   ),
}

我想澄清一下:我只能使用 ActiveRecord

1 个答案:

答案 0 :(得分:0)

我建议你使用这个简单的方法

$criteria = new CDbCriteria;
$criteria->join = 'LEFT JOIN (SELECT * FROM address ORDER BY address.type) as addresses
ON addresses.address != "" AND addresses.contractor_id = t.id';
$criteria->condition = 't.type=:type AND (t.name LIKE :name OR addresses.address LIKE :name))';
$criteria->params = ['type'=>$type, 'name'=>'%'.$name.'%'];
$criteria->group = 't.id';
$models = Contractor::model()->findAll($criteria);