Yii2: check exist ActiveRecord model in database

前端 未结 2 954
半阙折子戏
半阙折子戏 2021-01-03 19:45

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

2条回答
  •  孤独总比滥情好
    2021-01-03 20:21

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

提交回复
热议问题