[英]Laravel : Hasmany relationship returning empty results
i have 3 tables我有 3 张桌子
as below如下
Shops商店
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.