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
Package Table
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.