'Laravel Eloquent find most similar relations
so I'm trying to write an eloquent query, where I find similar models.
Let's say, I have three models ModelA and they have a 1:n relation to the model ModelB.
- ModalA 1 relation to ModelB a,b,c
- ModelA 2 relation to ModelB a,d,e
- ModelA 3 relation to ModelB a,c,e
I would like to make a simple query, where som thing like this happens with ModelA 1:
// pseudo code
$model->getMostSimilarRelations('modelBs') // = ModelA 3 --> because 2 relations similar found
So I was thinking, there is maybe a way like:
// pseudo code
$similars = ModelA::whereHas('modalBs', ['at_least_matching', 1, $relation_ids ])->get();
The best case would be, to return the count of the matching realtions, like:
[
'modalA' => ['id' => 3, 'hits' => 2],
'modalA' => ['id' => 2, 'hits' => 1],
]
Since I don't want to loop manually through all possible relations, I wonder if there is a Eloquent way to solve this? I'm using Laravel since many years, but I never saw something in that way. But maybe I was just missing it.
I appreciate any idea on this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
