Yii2:检查数据库中是否存在ActiveRecord模型
如何检查数据库中模型是否存在?在 Yii 1 版本中,情况就是这样User::model()->exist()
如何检查数据库中模型是否存在?在 Yii 1 版本中,情况就是这样User::model()->exist()
在 Yii2 中,您可以添加到查询链中:exists()
User::find()
->where( [ 'id' => 1 ] )
->exists();
(生成的 SQL 如下所示:。)SELECT 1 FROM `tbl_user` WHERE `id`=1
以下是来自 Yii2 源代码的 Query->exists():
:
/**
* 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();
}
if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
{
//....... Your code Here ......
}
http://yii2ideas.blogspot.in/2017/06/yii2-database-operations.html