如果来自查询

时间:2017-06-26 11:35:26

标签: mysql yii yii2

我的Mysql数据库中有很多查询。查询就像这个adn正常工作。

 SET @cleaning = 'cleaning';
        SET @one_bar = 'one bar';
        SET @test_periodic = 'test_periodic';
        SET @repairs = 'repair';

        SELECT ir.id, ir.no_surat, @cleaning as tagihan,tc.`level`, tc.cleaning as nominal FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_cleaning tc
        ON re.id = tc.repair_estimate_id

        UNION ALL

        SELECT ir.id, ir.no_surat,  @one_bar as tagihan, tob.`level`, tob.one_bar as nominal
            FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_one_bar tob
        ON re.id = tob.repair_estimate_id
        UNION ALL

        SELECT ir.id, ir.no_surat,  @test_periodic as tagihan,
                ttp.`level`, IFNULL(ttp.years2,ttp.years5)  as nominal
            FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_test_periodic ttp
        ON re.id = ttp.repair_estimate_id
        GROUP by ttp.id
        UNION ALL
        SELECT ir.id, ir.no_surat,  @repairs as tagihan,
                tr.`level`, tr.`repair` as nominal
            FROM ydepotras_estimator.repair_estimate re
        LEFT JOIN ydepotras_estimator.inspection_report ir
        ON re.inspection_id = ir.id
        INNER JOIN ydepotras_finance.tagihan_repair tr
        ON re.id = tr.repair_estimate_id
        ORDER BY no_surat

现在Yii2已开启。 此查询将变为$ dataProvider,然后,如果使用ActiveRecord,则会非常复杂。

我更喜欢像这样使用SQLDataProvider:

$query = 'The query from above'

 $dataProvider  = new SqlDataProvider([
        'sql' => $query,
        'totalCount' => 100,
    ]);

 return $dataProvider->getModels();

但它给了我:

Database Exception – yii\db\Exception
  SQLSTATE[HY000]: General error

1 个答案:

答案 0 :(得分:1)

事实上你没有为你的mysql var赋值,你可以直接使用值代替var

    SELECT ir.id, ir.no_surat, 'cleaning' as tagihan,tc.`level`, tc.cleaning as nominal FROM ydepotras_estimator.repair_estimate re
    LEFT JOIN ydepotras_estimator.inspection_report ir
    ON re.inspection_id = ir.id
    INNER JOIN ydepotras_finance.tagihan_cleaning tc
    ON re.id = tc.repair_estimate_id

或使用绑定参数

  $params = [':cleaning' => 'cleaning];
  $sql= Yii::$app->db->createCommand("
          SELECT ir.id, ir.no_surat, :cleaning as tagihan,tc.`level`, tc.cleaning as nominal FROM ydepotras_estimator.repair_estimate re
          LEFT JOIN ydepotras_estimator.inspection_report ir
          ON re.inspection_id = ir.id
          INNER JOIN ydepotras_finance.tagihan_cleaning tc
          ON re.id = tc.repair_estimate_id )
             ->bindValues($params);