我在Laravel 9项目中工作,只需要显示深度嵌套关系中有记录的记录,在我的例子中是tiers
。
我现在的关系仍然返回给我pingtree_entries
,即使tiers
是空的,我错过了什么?
下面是我的顶级查询:
$pingtree = Pingtree::where('company_id', $company_id)
->where('id', $id)
->has('pingtree_entries.tiers')
->with('pingtree_entries.tiers')
->first();
这应该是这样的:
按公司ID和ID获取我的Pingtree
,其中我的层与具有多个0层的Pingtree的pingtree_entries相关联。
我的Pingtree模型定义了:
/**
* Get the pingtrees that the model has.
*/
public function pingtree_entries()
{
return $this->hasMany(PingtreeEntry::class);
}
我的PingtreeEntry模型定义:
/**
* Get the buyer tier that the model has.
*/
public function tiers()
{
return $this->hasMany(BuyerTier::class, 'id', 'buyer_tier_id');
}
这是通过 Postman 输出以下内容:
{
"model": {
"id": 1,
"user_id": 1,
"company_id": 1,
"pick_chance": 4,
"name": "omnis iusto consequatur",
"description": "Hic nihil suscipit error.",
"is_enabled": false,
"created_at": "2023-01-27T14:15:26.000000Z",
"updated_at": "2023-01-27T14:15:26.000000Z",
"deleted_at": null,
"is_deleting": false,
"pingtree_entries": [
{
"id": 1,
"user_id": 1,
"company_id": 1,
"buyer_id": 2,
"buyer_tier_id": 4,
"pingtree_id": 1,
"pingtree_group_id": null,
"processing_order": 1,
"is_enabled": true,
"created_at": "2023-01-27T14:15:26.000000Z",
"updated_at": "2023-01-27T14:15:26.000000Z",
"deleted_at": null,
"tiers": [
{
"id": 4,
"user_id": 1,
"company_id": 1,
"buyer_id": 2,
"country_id": 2,
"product_id": 3,
"name": "dignissimos voluptas et",
"description": "Dolore tempora et maxime nam.",
"processing_class": "et",
"is_default": false,
"is_enabled": false,
"created_at": "2023-01-27T14:15:25.000000Z",
"updated_at": "2023-01-27T14:15:25.000000Z",
"deleted_at": null,
"is_deleting": false
}
]
},
{
"id": 3,
"user_id": 1,
"company_id": 1,
"buyer_id": null,
"buyer_tier_id": null,
"pingtree_id": 1,
"pingtree_group_id": 1,
"processing_order": 1,
"is_enabled": false,
"created_at": "2023-01-27T14:15:26.000000Z",
"updated_at": "2023-01-27T14:15:26.000000Z",
"deleted_at": null,
"tiers": []
}
]
}
}
注意,最后一个PingtreeEntry
没有层,所以我根本不想展示整个PingtreeEntry
模型。
尝试使用whereHas
$pingtree = Pingtree::where('company_id', $company_id)
->where('id', $id)
->whereHas('pingtree_entries.tiers')
->with('pingtree_entries.tiers.buyer')
->first();
1条答案
按热度按时间ev7lccsx1#
用途: