DBでモデルの存在を確認するには? Yii 1 バージョンではそうでした
User::model()->exist()
39851 次
2 に答える
55
Yii2 ではexists()
、クエリ チェーンに以下を追加できます。
User::find()
->where( [ 'id' => 1 ] )
->exists();
(生成された SQL は次のようになりますSELECT 1 FROM `tbl_user` WHERE `id`=1
。)
これはQuery->exists()
Yii2ソースからのものです:
/**
* 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();
}
于 2014-01-27T07:03:13.863 に答える
2
if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
{
//....... Your code Here ......
}
http://yii2ideas.blogspot.in/2017/06/yii2-database-operations.html
于 2017-06-25T09:07:27.770 に答える