简体   繁体   中英

Laravel : Hasmany relationship returning empty results

i have 3 tables

  1. shops
  2. packages
  3. shop_packages

as below

Shops

在此处输入图像描述

Packages

在此处输入图像描述

Shop Packages在此处输入图像描述

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

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');
    }

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM