Yii2: check exist ActiveRecord model in database

别说谁变了你拦得住时间么 提交于 2019-12-22 01:33:26

问题


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


回答1:


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

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

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

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

/**
 * 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();
}



回答2:


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

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



来源:https://stackoverflow.com/questions/21362301/yii2-check-exist-activerecord-model-in-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!