lundi 7 janvier 2019

How to get rows in Eloquent ordered by having most specific relationships?

I have a project in Laravel 5.1 with three tables: articles, tags and a pivot table to save many-to-many relationships: article_tag table.
I need to get all articles related by tags to a specific article, assigning a major number or relevance to those articles that have major number of coincidences by tag. So, first ones would be those which are "more related". For example, if I require all articles with tag_id #1 and #2, and if article A have both tags but article B have only one coincidence, I want get both articles ordered in sequence: A, B.

I think I can do it with a mysql statement:

SELECT articles.*, count(*) as tags_count 
FROM article_tag, articles 
WHERE tag_id in (1,2) 
AND articles.id = article_tag.article_id 
GROUP BY article_id 
ORDER BY tags_count DESC

But I want to use Eloquent. How can I approach it?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire