简体   繁体   English

Yii2:如何检查activeRecord模型是否为空

[英]Yii2: How to check if activeRecord Model is Empty

I am trying to fetch data from database like this: 我正在尝试从数据库中获取数据,如下所示:

$model = ProductFiles::findAll(['product_id' => $product_id]);

When I check count($model) , it returns as 0 if the model is empty and when the same model is rendered to view, it returns count($model) as 1 . 当我检查count($model) ,如果模型为空,则返回0 ;当呈现相同模型以查看时,它返回count($model)1 So, I was wondering if there is any way to check Yii2 activeRecord object, if it is empty or not (I tried isset but the same result). 因此,我想知道是否有任何方法可以检查Yii2 activeRecord对象是否为空(我尝试过isset但结果相同)。 any help is highly appreciated. 非常感谢您的帮助。

I'm not sure why this is happening in your case - it would be good to see the code of the controller's action responsible for passing the $model to view. 我不确定在您的情况下为什么会发生这种情况-最好查看负责传递$model的控制器操作代码。

As for the checking if ActiveRecord has been fetched - usually empty() is more than enough. 至于是否已经获取ActiveRecord的检查-通常empty()绰绰有余。

  • Static method findOne() returns instance of ActiveRecord or null if condition is not met. 静态方法findOne()返回ActiveRecord的实例;如果不满足条件,则返回null
  • Static method findAll() returns array of ActiveRecord instances or empty array if condition is not met. 静态方法findAll()返回ActiveRecord实例的数组;如果不满足条件,则返回空数组。

In both cases empty() returns false if $model has been fetched or true otherwise. 在这两种情况下,如果已获取$modelempty()返回false否则返回true

if ($model instanceof ProductFiles) {}

使用instanceof可以发现对象是否有记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM