yii cdbcriteria:复杂的连接

Acc*_*ccu 2 yii

我最近使用Yii开始了一个项目,我正在尝试习惯查询构建器.现在,我想使用连接进行查询并访问查询中的连接表数据,但我无法使以下工作:

我的(简化的)db-tables:

customer(#id,name)
employee(#id,name)
customer_employee(#customerid,#employeeid)
accounting(#id,customerid,started_date,finished_date,month,year)

  • 客户与员工之间的多对多关系
  • 客户与会计之间的一对多关系

我想执行以下查询,该查询将选择与某个员工关联的所有客户并显示其会计状态(started_date&finished_date)(如果适用)(否则为null).

以下查询工作正常,只是我无法使用cdbcriteria和Yii查询构建器:(同样,硬编码的id仅适用于此示例)

SELECT name, started_date, finished_date
FROM customer
RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid
LEFT JOIN accounting ON customer.id=accounting.customerid
WHERE customer_employee.employeeid=2';
Run Code Online (Sandbox Code Playgroud)

请帮忙!

dan*_*opa 5

1. createCommand

Yii::app()->db->createCommand()
  ->select('name, started_date, finished_date')
  ->from('customer c')
  ->rightJoin('customer_employee ce', 'c.id=ce.customerid')
  ->leftJoin('accounting a', 'c.id=a.customerid')
  ->where('ce.employeeid=:id', array(':id'=>2))
  ->queryRow();
Run Code Online (Sandbox Code Playgroud)

2. CdbCriteria

$criteria = new CDbCriteria;
$criteria->select    = 'name, started_date, finished_date';
$criteria->join      = 'RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid ';
$criteria->join     .= 'LEFT JOIN accounting ON customer.id=accounting.customerid';
$criteria->condition = 'customer_employee.employeeid=:id';
$criteria->params    = array(':id'=>2);

$customers = Customers::model()->find($criteria);
Run Code Online (Sandbox Code Playgroud)

*.不要忘记规则:http://www.yiiframework.com/doc/guide/1.1/en/database.arr

我没有测试过您的SQL,但如果为您工作,这些应该也适用于Yii.