Saani
Saani

Reputation: 782

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.

Upvotes: 5

Views: 10007

Answers (2)

Milan Suthar
Milan Suthar

Reputation: 352

if ($model instanceof ProductFiles) {}

Using instanceof you can find if object has record or not.

Upvotes: 0

Bizley
Bizley

Reputation: 18021

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.

Upvotes: 9

Related Questions