How to check existence of model in DB?
In Yii 1 version it was so
User::model()->exist()
Asked
Active
Viewed 4.3k times
2 Answers
55
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();
}

ippi
- 9,857
- 2
- 39
- 50
-
mine does not working in where clause, what do I have to do? – Mohammad Aghayari Apr 30 '18 at 13:50
-
Does it return a true/false or 1/0? I would like to return a boolean. – Roby Sottini Nov 26 '18 at 11:41
-
`* @return boolean whether the query result contains any row of data.` – ippi Nov 26 '18 at 11:49
-
Thank you @ippi Up + – user206 Aug 20 '20 at 11:28
2
if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
{
//....... Your code Here ......
}
http://yii2ideas.blogspot.in/2017/06/yii2-database-operations.html

Maher
- 2,517
- 1
- 19
- 32

user7641341
- 169
- 1
- 5