John Davidson

php - Laravel how to get posts by different columns?

0 comments
Message:


How can I get a list of posts by the following principle:


Get by post creation date created_at. But if post_top_date is not equal to the steering wheel, take the date from this column. This is the date of raising the post above all.


post_top_date = dateTime column


This method is currently being used. But it doesn't work correctly.


PostModel::where('status', 1)
->where('moderation','=', 0)
->where('category_id', '=', $this_category_id)
->orderBy('created_at')->paginate($ElPerPageCategory);


My Answer:
> One way to achieve this is by using the `orderBy` method in Laravel to sort the posts by the `created_at` column first and then by the `post_top_date` column if it is not equal to the current date. Here's an example of how you can do this:

php
$posts = PostModel::where('status', 1)
->orderBy('created_at', 'desc')
->orderByRaw("CASE WHEN post_top_date = CURDATE() THEN 1 ELSE 0 END DESC")
->get();


In this code snippet, we first filter the posts by the `status` column with a value of 1. Then, we use the `orderBy` method to sort the posts by the `created_at` column in descending order. Finally, we use the `orderByRaw` method to add a custom sorting logic based on the `post_top_date` column. If the `post_top_date` is equal to the current date, we give it a higher priority by sorting it before other posts.

This should give you a list of posts sorted by the `created_at` column first and then by the `post_top_date` column if it is not equal to the current date.

Rate this post

5 of 5 based on 2998 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us