【问题标题】:Yii2: check exist ActiveRecord model in databaseYii2:检查数据库中是否存在 ActiveRecord 模型
【发布时间】:2014-01-26 10:30:07
【问题描述】:

如何检查数据库中模型的存在? 在 Yii 1 版本中是这样的 User::model()->exist()

【问题讨论】:

    标签: php yii2


    【解决方案1】:

    在 Yii2 中,您可以将 exists() 添加到您的查询链中:

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

    (生成的 SQL 如下所示:SELECT 1 FROM `tbl_user` WHERE `id`=1。)

    这里是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();
    }
    

    【讨论】:

    • mine 在 where 子句中不起作用,我该怎么办?
    • 它返回真/假还是 1/0?我想返回一个布尔值。
    • * @return boolean whether the query result contains any row of data.
    • 谢谢@ippi Up +
    【解决方案2】:
    if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
    {                    
      //....... Your code Here ......
    } 
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2015-05-10
      • 2016-11-30
      • 2010-10-22
      相关资源
      最近更新 更多