Yii2:检查数据库中是否存在ActiveRecord模型

Het*_*ett 24 php yii2

如何在DB中检查模型的存在?在Yii 1版本中它是如此 User::model()->exist()

ipp*_*ppi 48

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

User::find()
    ->where( [ 'id' => 1 ] )
    ->exists(); 
Run Code Online (Sandbox Code Playgroud)

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

这是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();
}
Run Code Online (Sandbox Code Playgroud)