简体   繁体   English

Laravel:Hasmany 关系返回空结果

[英]Laravel : Hasmany relationship returning empty results

i have 3 tables我有 3 张桌子

  1. shops商店
  2. packages
  3. shop_packages 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.它适用于 Laravel 9,如果您的 Laravel 版本低于检查many-to-many-polymorphic-relations以获取适合您版本的文档。

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 :在 Package 模型中,您应该具有以下内容:

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

Otherwise in Shop model you should have :否则在 Shop 模型中你应该有:

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

You have to use the appropriate relationship regarding to your needs.您必须根据您的需要使用适当的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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