staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Many to One and Many To Many #98

Closed GiuseppeMobijay closed 4 years ago

GiuseppeMobijay commented 4 years ago

Hi, I can't setup my relations.

I have "ServiceLog" Model [with relation defined by belongsTo to "Tool" model] I have "Tool" Model [with relation by belongsTo "ToolGroup" Model]

I need to access ToolGroup in ServiceLog Model.

recap: ServiceLog - many to one- Tool - many to many - Group

I try with

return $this->hasManyDeep( 'App\Entities\ToolGroup', ['App\Entities\Tool','tool_has_group'], )

But I got error, because the query generated search for ServiceLog id in Tool table but it is the inverse.

Can you help me in understanding the problem?

Thank you very much for sharing you package with us.

staudenmeir commented 4 years ago

Use this relationship (assuming the foreign key is called tool_id):

return $this->hasManyDeep(
    'App\Entities\ToolGroup',
    ['App\Entities\Tool', 'tool_has_group'],
    ['id'],
    ['tool_id']
);
GiuseppeMobijay commented 4 years ago

Thank you for you response.

In this way, the query generated had an ambigous id field.

the generated sql is (the ambigous part is on id = 12073)

select count(*) as aggregate from `service_log` 
where ((exists (select * from `tool_group` inner join `tools_has_tool_group` 
on `tools_has_tool_group`.`tool_group_id` = `tool_group`.`id` 
inner join `tools` on `tools`.`id` = `tools_has_tool_group`.`attrezzatura_id` 
where `tools`.`deleted_at` is null and `…ts 
(select * from `tool_group` inner join `tools_has_tool_group` on `tools_has_tool_group`.`tool_group_id` = `tool_group`.`id` 
inner join `tools` on `tools`.`id` = `tools_has_tool_group`.`attrezzatura_id` 
where `tools`.`deleted_at` is null 
and `service_log`.`tools_id` = `tools`.`id` 
and `id` = 12073 
and `tools`.`deleted_at` is null 
and `tool_group`.`deleted_at` is null))))"
staudenmeir commented 4 years ago

How are you using the relationship in your query?

GiuseppeMobijay commented 4 years ago

Hi Jonas, I double check the code, and define the other local / foreign keys and now it works fine.

thank you very much for sharing you time