2014-01-26 2 views

ответ

39

В Yii2 вы можете добавить exists() к цепочке запросов:

User::find() 
    ->where([ 'id' => 1 ]) 
    ->exists(); 

(Сгенерированный SQL выглядит следующим образом:. SELECT 1 FROM `tbl_user` WHERE `id`=1)

Здесь также Query->exists() взяты из the 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 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; 
    } 
Смежные вопросы