Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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). any help is highly appreciated.

like image 379
Saani Avatar asked Feb 05 '23 15:02

Saani


1 Answers

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.

As for the checking if ActiveRecord has been fetched - usually empty() is more than enough.

  • Static method findOne() returns instance of ActiveRecord or null if condition is not met.
  • Static method findAll() returns array of ActiveRecord instances or empty array if condition is not met.

In both cases empty() returns false if $model has been fetched or true otherwise.

like image 84
Bizley Avatar answered Feb 15 '23 04:02

Bizley