php Yii2:检查数据库中存在的 ActiveRecord 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21362301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:04:34  来源:igfitidea点击:

Yii2: check exist ActiveRecord model in database

phpyii2

提问by Hett

How to check existence of model in DB? In Yii 1 version it was so User::model()->exist()

如何检查数据库中模型的存在?在 Yii 1 版本中是这样 User::model()->exist()

回答by ippi

In Yii2 you can add exists()to your query chain:

在 Yii2 中,您可以添加exists()到查询链中:

User::find()
    ->where( [ 'id' => 1 ] )
    ->exists(); 

(The generated SQL looks like this: SELECT 1 FROM `tbl_user` WHERE `id`=1.)

(生成的 SQL 如下所示:SELECT 1 FROM `tbl_user` WHERE `id`=1.)

Here is Query->exists()from Yii2 source:

这是Query->exists()来自 Yii2 的源代码

/**
 * Returns a value indicating whether the query result contains any row of data.
 * @param Connection $db the database connection used to generate the SQL statement.
 * If this parameter is not given, the `db` application component will be used.
 * @return bool whether the query result contains any row of data.
 */
public function exists($db = null)
{
    if ($this->emulateExecution) {
        return false;
    }
    $command = $this->createCommand($db);
    $params = $command->params;
    $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
    $command->bindValues($params);
    return (bool) $command->queryScalar();
}

回答by Shaneesh P

if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
{                    
  //....... Your code Here ......
} 

http://yii2ideas.blogspot.in/2017/06/yii2-database-operations.html

http://yii2ideas.blogspot.in/2017/06/yii2-database-operations.html