Friday 7 October 2016

Yii2 check if record is exist

In Yii2 we can check if record is exist or not through exist function

Example:

$exist = Record::find()->where( [ 'id' => 1 ] )->exists(); 
if($exist){
   echo "Record is exist";
}else{
   echo "No Record is exist";
}
The generated SQL looks like this: 
SELECT 1 FROM `tbl_record` WHERE `id`=1.
Query->exists()taken from the Yii2 source.

Here is library function code. (reference only)
     /**
     * 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 boolean whether the query result contains any row of data.
     */
    public function exists($db = null)
    {
            $select = $this->select;
            $this->select = [new Expression('1')];
            $command = $this->createCommand($db);
            $this->select = $select;
            return $command->queryScalar() !== false;
    }