使用yii2模型进行sql查询

时间:2017-08-31 08:34:23

标签: php yii2

我正在尝试执行此查询

         $command = $connection->createCommand("
                    SELECT 
                     tbl_checklist.report_val AS item
                     FROM tbl_checks
                        LEFT JOIN tbl_checklist ON tbl_checklist.id = tbl_checks.check_id
                        WHERE truck_id = ".$value->id."
                        "
                 );

         $results = $command->queryAll();

以上工作但我想使用模型

执行相同的操作

所以我试过了

$results = TblChecks::find()
           ->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
           ->where(["truck_id"=>$value->id])
           ->all();

如何在模型流

中添加SELECT tbl_checklist.report_val AS item

3 个答案:

答案 0 :(得分:0)

你应该这样试试

$results = TblChecks::find()->select(["tbl_checklist.report_val AS item","tbl_checks.*"])
           ->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
           ->where(["truck_id"=>$value->id])
           ->all();

答案 1 :(得分:0)

尝试这种方式,我希望它能解决您的问题。

$results = TblChecks::find()
       ->select[tbl_checklist.report_val AS item]
       ->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
       ->where(["truck_id"=>$value->id])
       ->all();

答案 2 :(得分:-1)

您应该使用select()功能:

$results = TblChecks::find()
           ->select('tbl_checklist.report_val AS item')
           ->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
           ->where(["truck_id"=>$value->id])
           ->all();

在模型中添加属性$item