mercredi 10 octobre 2018

laravel eloquent: Eloquent relation needs to return something when there is no data instead of returning null object

I have this relation on my product model.

public function productInventory(){
        return $this->hasOne('App\Models\Ecommerce\Inventory', 'product_id')->where('is_deleted', 0);
}

Sometimes, i may not have inserted that specific product in my inventory table. So, this relation is still in play with view but will try to get the productInventory->price which will throw an error, cannot get price of null object. So, I've done this now which is just a simple thing to do. But the count is 1 or greater than 1, because there are other products. So how will I be able to return only null for that specific product which has no data in the inventory table?

public function productInventory(){
        $has_inv = Inventory::where('product_id',$this->id)->where('is_deleted', 0)->count();        
        if($has_inv < 1){
            return null;
        }
        return $this->hasOne('App\Models\Ecommerce\Inventory', 'product_id')->where('is_deleted', 0);
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire