yii2使用ActiveRecord在连接中创建另一个查询

时间:2016-11-17 07:28:17

标签: mysql join activerecord yii2

我有一个连接查询,我需要用活动记录重新制作..问题是查询非常难,我不知道如何在连接中进行连接...

查询:

$query = Product::find()
            ->select([
                'p.*',
                'pv.Units as SaleUnits',
                'pv.Total as  Pv',
            ])
            ->leftJoin('
            (select 
            cl.campaign_list_status
            p.id,
            p.admin_title,
            ao.article,
            sum(ao.article) as Articles,
            sum(ao.units) as Units,
            TRUNCATE(sum(spo.total_price),2) as Total
            from campaign_list cl
                inner join campaign_article ca on ca.id_campaign_list=cl.id 
                group by ao.article) pv','pv.id=p.id')
            ->all();

甚至可以使用ActiveRecord吗?

2 个答案:

答案 0 :(得分:0)

这更简单(仅作为想法):

$query = Product::find()
        ->select([
            'p.*',
            'sum(units) as SaleUnits',
            'sum(article) as  Pv',
        ])
        ->leftJoin('campaign_article','???')
        ->leftJoin('campaign_list','???')
        ->groupBy('article')
        ->all();

答案 1 :(得分:0)

U可以在Yii2中执行相同的SQL查询。

$connection = Yii::$app->getDb();

        $command = $connection->createCommand("Your complete sql query");
        $rows = $command->queryAll();