Home > database >  Laravel : Hasmany relationship returning empty results
Laravel : Hasmany relationship returning empty results

Time:05-25

i have 3 tables

  1. shops
  2. packages
  3. shop_packages

as below

Shops

enter image description here

Packages

enter image description here

Shop Packages enter image description here

i am using following relationship in Shop Model

 public  function  packages(){
    return $this->belongsToMany(Package::class,'shop_packages','shop_id','package_id');
 }

and below in Package Model

 public  function  shop(){
     return $this->belongsToMany(Shop::class,'shop_packages','package_id','shop_id');
 }

when i try to get

 Package::with('shop')->get();

it returns me packages but shops remain empty can someone please guide me how can i fix this

CodePudding user response:

It is applicable for Laravel 9, If your Laravel version is lower than check the many-to-many-polymorphic-relations for documenton appropriate your version.

In Package Model

/**
     * Get all of the shops for the package.
     */
    public function shops()
    {
        return $this->belongsToMany(Shop::class, 'shop_packages');
    }

In Shop Model

/**
     * Get all of the packages for the package.
     */
    public function packages()
    {
        return $this->belongsToMany(Package::class, 'shop_packages');
    }

CodePudding user response:

Your DB capture does not correspond to your relationships.

In Package model you should have something like :

public function packages(){
   return $this->belongsToMany(Shop::class,'shop_packages');
}

Otherwise in Shop model you should have :

public function shops(){
   return $this->hasMany(Package::class);
}

You have to use the appropriate relationship regarding to your needs.

  • Related