Home > Enterprise >  Laravel : BelongstoMany relationship implementation
Laravel : BelongstoMany relationship implementation

Time:06-30

i have following tables

1.Shops  (shop_id , company_id , name, latitude, logntitude, phone)

2.packages(package_id, company_id, cost, value, expire_date)

3.shop_packages (package_id, shop_id)

and i am trying to access this shops associated with package as below

Package Model

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

Shop Model

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

now when i try below it returns me shop with empty result while there is data available ,

 Package::with('shop')->where('package_id',$request['package_id'])->first();

i am using laravel 8.x for this project . Can someone please help me to sort the issue

Shop Table

enter image description here

Package Table

enter image description here

shop_packages shop_packages

CodePudding user response:

You entered the wrong foreign key in the relation. The belongsToMany relation should be declared like this

Package Model

public  function  shops():BelongsToMany{
    return $this->belongsToMany(Shop::class,'shop_packages','package_id','shop_id');
    //you can also just ignore the foreign keys since they follow naming standards
    //return $this->belongsToMany(Shop::class,'shop_packages');
}

Shop Model

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

You should also use plural to better express the many to many relation

Package::with('shops')->where('package_id',$request['package_id'])->first();
  • Related