2

私は最近、Yii を使用してプロジェクトを開始し、クエリ ビルダーに慣れようとしています。今、結合を使用してクエリを作成し、クエリで結合テーブルのデータにアクセスしたいのですが、次を機能させることができませんでした:

私の(簡略化された)dbテーブル:

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

  • 顧客と従業員の間の多対多の関係
  • 顧客と経理の1対多の関係

次のクエリを実行すると、特定の従業員に関連付けられているすべての顧客が選択され、該当する場合は会計ステータス (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';

助けてください!

4

4 に答える 4

5

1.create コマンド

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();

2.Cdb基準

$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 でも働くはずです。

于 2013-02-08T14:17:44.770 に答える
2
$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-10-19T06:34:23.713 に答える
1

今日は少し遅くなりましたが、私のブログのこの投稿を参照してください。この投稿では、この難しいサブクエリ スタイルの SQL の両方の部分について説明しています。

第一に、他のモデルの属性に依存する検索を構築する第二に、完全な Yii AR モデルを使用せずに関連モデルを単純に使用する

http://sudwebdesign.com/yii-parameterising-a-sub-select-in-sql-builder/932

于 2012-11-06T17:04:24.970 に答える
0

私はそれを実行していませんが、次のようなものが必要です

$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);
于 2012-06-13T13:34:13.380 に答える