W
W
wagwandude2017-08-23 15:19:10
Laravel
wagwandude, 2017-08-23 15:19:10

How to display the latest updates?

Hello.
You need to display the latest articles from the table as follows:

[ Звезды ]          [ Путешествия ]           [ Девушки ] 
5 записей           5 записей                 5 записей

Please note that one article can be added to all three categories. Accordingly, display it only in the block of the first category, and remove it from the other two and replace it with another article from the same category, which, in turn, is not included in the other output categories.
There are tables:
1. categories - [id, name, slug, display_home - it is important to note that display_home in where is equal to 1]
2. item_category - [id, post_id, category_id]
3. posts - many fields, but only - [ id, title, slug]
How can I make the most correct request?
I could build a new array by iterating through all the articles and calling a query to display the categories in a loop, but that doesn't work.
How can you write something similar using Query Builder in Laravel?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Parotikov, 2017-08-31
@wagwandude

query-buldera requests:

//достаем категории для главной
$categories = Category::where('display_home', 1)->get('id', 'name', 'slug');

//сюда будем схоронять посты, которые не должны повторяться
$posts_exclude = collection();

//для каждой категории
foreach ($categories as $category) {
  
  $posts_array[$category->title] = Post:: //ищем посты,
    whereHas('categories', function ($q) use ($category) { //у которых категория
      $q->where('id', $category->id); // одна из найденных для главной,
    })
    ->whereNotIn('id', $posts_exclude->pluck('id')) // и постов нет в исключаемых
    ->get('id', 'title', 'slug'); // только с нужными полями
  $posts_exclude->merge($posts_array[$category->id]); // добавили найденные посты в коллекцию с исключаемыми
}

Then we already output an array with posts (pseudocode, this must be rewritten in the blade):
<ul>
foreach ($posts_array as $category => $posts) {
  <li>
    $category //ключ основного массива - название категории 
    <ul>
    foreach ($posts as $post) { //значение элементов основного массива - набор постов из категории
      <li>$post->title</li>
    }
    </ul>
  </li>
}
</ul>

That is, we get n+1 queries, where n is the number of categories.
It's in the query-builder style. You can, in principle, write one raw request, but this is already outside the topic.
A complex single query-builder query, I suppose, can be written, but I don’t see the point, because it will be unsupported. Yes, and it's all possible to cache, so it's not about speed.
ps: There is no place to check the code, I wrote it from memory. I hope the train of thought is clear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question