【问题标题】:Yii2: How can I get table columns which have equal not empty data in two columns in the same recordYii2:如何在同一记录的两列中获取具有相等非空数据的表列
【发布时间】:2017-06-15 19:37:27
【问题描述】:

我想使用 ActiveQuery 从 SQLite 数据库中选择字段,其中两列具有相等的非空值。

我需要这样的 SQL 示例:

SELECT * FROM messages WHERE msg_sent = 0 AND file_size = downloaded_size AND file_sha1 = downloaded_sha1

【问题讨论】:

    标签: sqlite activerecord yii2


    【解决方案1】:

    我已经要求这样的解决方案:

    use yii\db\Expression;
    
        $messages = Messages::find()
            ->where([
                'file_downloaded' => 1,
            ])
            ->andWhere(['=', 'msg_sent', 0])
            ->andWhere(['=', 'file_size', new Expression('`downloaded_size`')])
            ->andWhere(['=', 'file_sha1', new Expression('`downloaded_sha1`')])
            ->asArray()
            ->all();
    
    // to debug raw SQL I have used the following:
    $query = = Messages::find()
                ->where([
                    'file_downloaded' => 1,
                ])
                ->andWhere(['=', 'msg_sent', 0])
                ->andWhere(['=', 'file_size', new Expression('`downloaded_size`')])
                ->andWhere(['=', 'file_sha1', new Expression('`downloaded_sha1`')]);
    echo var_dump($query->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql) . PHP_EOL;
    

    【讨论】:

      【解决方案2】:

      假设你的 activeRecord 类名为 MyModel

        $models = MyModel::find()
                ->where(['msg_sent'=> 0, 
                         'file_size'=>'downloaded_size',
                         'file_sha1' =>'downloaded_sha1'])
                ->all();
      

      如果不使用散列格式,您可以将文字格式用作

         $models = MyModel::find()
          ->where('msg_sent = 0 and file_size= downloaded_size and file_sha1 = downloaded_sha1')
          ->all();
      

      【讨论】:

      • 谢谢@scaisEdge,这是我尝试过的第一件事,但它不起作用。
      • 我有以下 SQL 然后我使用你的建议: string(149) "SELECT * FROM messages WHERE ((file_downloaded=1) AND (file_size='downloaded_size') AND (file_sha1='downloaded_sha1')) AND (msg_sent = 0)" 我需要 db 字段而不是带有列名的字符串
      • 答案已更新 .. 使用另一种格式 .. 希望有用
      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 2015-01-01
      • 2020-05-20
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多