2017-07-04 44 views
0

我已經有正確的SQL查詢,但現在我有問題來更改CakePHP的查詢。我該怎麼做才能獲得相同的SQL?提前致謝。如何轉換CakePHP的SQL查詢?

SELECT tests.id, tests.name,tests.tag_on, tests.status, tests.date_scheduled, tests.date_done, tests.remarks, 
field_user.name AS fielduser, sales_user.name AS salesuser 
FROM tests 
INNER JOIN users field_user ON (field_user.id = tests.field_user_id) 
INNER JOIN users sales_user ON (sales_user.id = tests.sales_user_id); 

這是我TestsController.php

public function index() 
{ 
     $this->paginate = ['limit' => 100, 'order' => ['date_scheduled' => 'asc'], 
     'contain' => ['Users','FieldUsers'], 
     'fields' => ['id', 'name', 'tag_on', 'status', 'date_scheduled', 'date_done', 'remarks', Users.id','Users.name','field_user_id','sales_user_id'], 
     'sortWhitelist' => ['id', 'name','tag_on', 'status', 'date_scheduled', 'date_done', 'remarks','Users.id','Users.name','field_user_id','sales_user_id'], 
     ]; 
    } 

這是我TestsTable.php

class TestsTable extends Table 
    { 

     public function initialize(array $config) 
     { 
      parent::initialize($config); 

      $this->table('tests'); 
      $this->displayField('name'); 
      $this->primaryKey('id'); 

      $this->belongsTo('Users', [ 
       'className' => 'Users', 
       'foreignKey' => 'sales_user_id', 
       'joinType' => 'INNER' 
      ]); 

      $this->belongsTo('FieldUsers', [ 
       'className' => 'Users', 
       'foreignKey' => 'field_user_id', 
       'joinType' => 'INNER' 
      ]); 

回答

1

您可以在蛋糕ORM的兩種方式做到這一點,我寫一個不同於2

$this->Tests->find('all') 
     ->contain(['Users', 'FieldUsers']) 
     ->select(['Tests.name', 'Tests.tag_on', 'Tests.status', 
      'FieldUsers.name'=>'fieldUser', 'Users.name'=>'userName']) 
     ->limit('100') 
     ->order(['date_scheduled' => 'asc']); 

您可以使用額外的2事情得到結果作爲數組。

->hydrate(false)->toArray(); //Must be at the end 

編碼快樂:)