BelongsToMany 独立子关系 - Laravel/Eloquent
模型结构:
FoodCategory
- hasMany:Food
Food
-belongsToMany:AccessoryGroup
|属于:FoodCategory
AccessoryGroup
- hasMany:Accessory
| belongsToMany:Food
Accessory
-belongsTo:AccessoryGroup
$foodCategories = FoodCategory
::with([
'foods',
'foods.accessory_groups',
'foods.accessory_groups.accessories',
])
->get();
$foodCategories->each(function($foodCategory) {
$foodCategoryId = $foodCategory->id;
$foodCategory->foods->each(function($food) use( $foodCategoryId ) {
$food->accessory_groups->each(function($accessoryGroup) use( $foodCategoryId ) {
$accessoryGroup->accessories->each(function($accessory) use( $foodCategoryId ) {
// accessory - not unique by different food grandparent realation
$accessory->parent_food_category_id = $foodCategoryId;
});
});
});
});
问题是当我设置$accessory->parent_food_category_id = $foodCategoryId;
最后一个相同配件覆盖“所有配件”的parent_food_category_id
值(具有相同的id) - (不同的食物
祖父母)。
是否可以轻松“克隆”belongsToMany
关系(在本例中是accessory_groups
)。与您更改其子项 (accessory
) 相比,不要更改所有相同的 accessories
(具有相同的 id)。
需要优化的解决方案。不要为每种食物
调用单独的sql -> accessory_group
关系(此问题的解决方案之一)
Model structure:
FoodCategory
- hasMany: Food
Food
- belongsToMany: AccessoryGroup
| belongsTo: FoodCategory
AccessoryGroup
- hasMany: Accessory
| belongsToMany: Food
Accessory
- belongsTo: AccessoryGroup
$foodCategories = FoodCategory
::with([
'foods',
'foods.accessory_groups',
'foods.accessory_groups.accessories',
])
->get();
$foodCategories->each(function($foodCategory) {
$foodCategoryId = $foodCategory->id;
$foodCategory->foods->each(function($food) use( $foodCategoryId ) {
$food->accessory_groups->each(function($accessoryGroup) use( $foodCategoryId ) {
$accessoryGroup->accessories->each(function($accessory) use( $foodCategoryId ) {
// accessory - not unique by different food grandparent realation
$accessory->parent_food_category_id = $foodCategoryId;
});
});
});
});
Problem is when i set $accessory->parent_food_category_id = $foodCategoryId;
last same accessory overrides parent_food_category_id
value for "all accessories" (with same id) - (diffrent food
grandparent).
Is it possible to easily "clone" belongsToMany
relation (in this case accessory_groups
). And than when you change their child (accessory
), to not change on all same accessories
(with same id).
Needed optimized solution. Not to call separate sql for every food
-> accessory_group
relation (One of the solutions for this problem)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的解决方案(使用复制模型方法)
My Solution (use replicate Model method)