laravel 4 relations - how display a top-5 ranking of records voted by users

后端 未结 2 1388
挽巷
挽巷 2021-01-19 15:43

I am creating a system of newsfeed, and as you can easily guess, it is beyond my skills. Please be kind to put me on the right track or provide something I can go on with.<

2条回答
  •  情歌与酒
    2021-01-19 16:21

    PROBLEM 4: SOLVED! (credit to @lukasgeiter)

    If you wish to display a ranking of items and limit the results to a particular tag defined in a pivot table, this is the solution:

    $events = Event1 (table name = 'events')

    For example, the tag would be war: defined in table eventtags

    Event nature are defined as

    id = '1' is name = 'wars' id = '2' is name = 'conflicts' pivot table, which assigns multiple tags: event_eventtags they are defined as id = '4'

    Example records for event_eventtags:

    id - event_id - eventtag_id

    1 - 45 - 1

    2 - 45 - 2

    Plain English: the Event1 #45 is tagged as war(#1) and conflict(#2)

    Now in order to print a list of 10 wars you should define your query in this way:

    $events= Entity::join('event_eventtags', function($q){
             $q->on('entity_id', '=', 'entities.id');
             $q->where('entitycapacitytypes_id', '=', 1);
         })->leftJoin('user_attitudes', function($q){
             $q->on('item_id', '=', 'entities.id');
             $q->where('item_type', '=', 'entity');
        })
        ->selectRaw('entities.*, SUM(user_attitudes.importance) AS importance')
        ->groupBy('entities.id')
        ->orderBy('importance', 'desc')
        ->take(10)
        ->get();
    

    The user_attitudes is part of voting system described in the original question. You can remove it and sort events by another method.

提交回复
热议问题