最近,我使用Yii启动了一个项目,我正在尝试适应查询构建器。现在,我想使用joins进行查询,并访问查询中的联接表的数据,但我无法让以下内容发挥作用:
我的(简化)数据库-表:
客户(#id,姓名)
雇员(#id,姓名)
customer_employee(#customerid,#employeeid)
会计(#id,customerid,started_date,finished_date,月,年)
客户之间的多对多关系和employee
之间的关系
我希望执行以下查询,该查询将选择与某个员工关联的所有客户,并显示其会计状态(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';请帮帮我!
发布于 2013-02-08 14:17:44
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();$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);*。别忘了规则:http://www.yiiframework.com/doc/guide/1.1/en/database.arr
我没有测试您的SQL,但是如果为您工作,它们也应该在Yii中工作。
发布于 2012-10-19 06:34:23
$criteria = new CDbCriteria();
$criteria->select = "name, started_date, finished_date";
$criteria->join = "RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid LEFT JOIN accounting ON customer.id=accounting.customerid";
$criteria->condition = "customer_employee.employeeid=2";
$models = Customer::model()->findAll($criteria);这是如何使用命令获取表customer_employee的数据
foreach($model as $value)
{
}发布于 2012-11-06 17:04:24
虽然有点晚了,但是在我的博客上看到了这篇文章,它涉及到这种困难的子查询样式SQL的两个部分。
首先,建立依赖于其他模型属性的搜索;其次,使用相关模型而不使用完整的Yii AR模型。
http://sudwebdesign.com/yii-parameterising-a-sub-select-in-sql-builder/932
https://stackoverflow.com/questions/11015311
复制相似问题