Yii2如何在哪里进行AND或OR条件分组?

问题描述 投票:40回答:8

我是Yii-2框架的新手。我如何使用activeQuery和模型在Yii-2框架中实现以下查询。

SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)

谢谢

php mysql activerecord yii yii2
8个回答
77
投票

您可以尝试以下方法:

//SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)
$model = arname()->find()
       ->andWhere(['user_id'=>[1,5,8]])
       ->andWhere(['or',
           ['status'=>1],
           ['verified'=>1]
       ])
       ->orWhere(['and',
           ['social_account'=>1],
           ['enable_social'=>1]
       ])
       ->all();

31
投票

尝试一下-

$query = (new \yii\db\Query())
            ->select('*')
            ->from('users u')
            ->where(['and',['u.user_id'=>[1,5,8]],['or','u.status=1','u.verified=1']])
            ->orWhere(['u.social_account'=>1,'u.enable_social'=>1]);
    $command = $query->createCommand();
    print_r ($command->sql);die;

more info


3
投票

我假设您已经了解Yii 2.0中的数据库配置,这与Yii 1.0版本中的基本相同。

如果要使用activeQuery,则需要先定义一个“ USERS”类:

<?php
    namespace app\models;
    use yii\db\ActiveRecord;

    class USERS extends ActiveRecord {
        public static function tableName()
        {
            return 'users';
        }
    }
?>

然后在使用时,可以如下编写:

<?
    $usr_data = USERS::find()->  
            ->where("user_id IN(1,5,8) AND (status = 1 OR verified = 1) OR (social_account = 1 AND enable_social = 1)")
            ->all();    
?>

我认为,活动查询为您提供了一种按子块分隔sql的方法。但是,当您遇到如此复杂的“ AND OR”条件时,应用它就没有任何意义。


3
投票

您也可以这样操作:


2
投票

使用MongoDB


0
投票

C0]的[where()函数也接受字符串作为其第一个参数,该字符串将在查询的ActiveQuery条件中使用。因此,最简单的方法是将这些条件置于WHERE函数中。


0
投票

首先使用OR


0
投票
(new \yii\db\Query())
            ->select(['id', 'client', 'ts', 'action'])
            ->from('log_client as log')
            ->orWhere(['action' => 'lock'])
            ->orWhere(['action' => 'rel'])
            ->andWhere(['in', 'client', $IDs])
            ->orderBy(['ts' => SORT_ASC])
            ->all();
© www.soinside.com 2019 - 2024. All rights reserved.