Zain Farooq
Zain Farooq

Reputation: 2964

Return relation if it counts greater than 0 else return other relation

I want to return a relation if it has results greater than 0 otherwise it should return other relation

public function default_product_image()
    {  
        if(count($this->ztecpc_product_images()->get()) > 0)
        {
            return $this->hasMany('App\ZtecpcProductImage','product_id','id')//if count > 0 then return this relation
                    ->select('id','product_id','image');
        }
        return $this->hasOne('App\ProductImagesModel','product_id','id')//else return this relation
                    ->where('main_image',1)
                    ->select('id','product_id','image');
    }

 public function ztecpc_product_images()
    {
        return $this->hasMany('App\ZtecpcProductImage','product_id','id')
                    ->select('id','product_id','image');
    }

I want to return return $this->hasMany('App\ZtecpcProductImage','product_id','id') ->select('id','product_id','image'); if ztecpc_product_images relation has the results greater than 0 otherwise it should return other relation in the function. My problem is that it is always return empty array which I guess it the if-condition if(count($this->ztecpc_product_images()->get()) > 0) is always true.

Upvotes: 0

Views: 447

Answers (2)

Urudin
Urudin

Reputation: 331

Change your if statement like that:

if($this->ztecpc_product_images()->count() > 0)

Upvotes: 1

Spholt
Spholt

Reputation: 4042

I think your guess is correct and I believe I know why:

$this->ztecpc_product_images

Will return an Eloquent Collection rather than an array. This is an object and will always return true even if empty.

Try replacing it with the following:

if ($this->ztecpc_product_images->isNotEmpty()) {
   ...
}

This uses the available Eloquent Collection methods to check for a lack of results.

Upvotes: 0

Related Questions