Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: check exist ActiveRecord model in database

Tags:

php

yii2

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

like image 272
Hett Avatar asked Jan 26 '14 10:01

Hett


People also ask

What is ActiveRecord in Yii2?

Active Record provides an object-oriented API for accessing data. An Active Record class is associated with a database table. Yii provides the Active Record support for the following relational databases − MySQL 4.1 or later.

What is active query in yii?

An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().


2 Answers

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(); } 
like image 135
ippi Avatar answered Nov 10 '22 06:11

ippi


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

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

like image 30
user7641341 Avatar answered Nov 10 '22 06:11

user7641341