Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Order by multiple meta fields #571

Open
moerphie opened this issue Aug 10, 2021 · 1 comment
Open

Order by multiple meta fields #571

moerphie opened this issue Aug 10, 2021 · 1 comment

Comments

@moerphie
Copy link

Hello,
is it possible to sort the results by multiple meta fields?

Current code:

Post::hasMeta(["is_available" => true])
      ->status("publish")
      ->type("post")
      ->join("postmeta", "postmeta.post_id", "id")
      ->where("meta_key", "visits")
      ->orderBy("meta_value", "desc")

But I want to order it by visits DESC, product_name ASC.

Is there any way?

@josedarci
Copy link

Yes, it is possible to sort the results by multiple meta fields using Corcel. Here's an example of how you can modify your code to achieve that:

Post::hasMeta(["is_available" => true])
    ->status("publish")
    ->type("post")
    ->join("postmeta as pm1", function ($join) {
        $join->on("pm1.post_id", "=", "posts.ID")
             ->where("pm1.meta_key", "visits");
    })
    ->join("postmeta as pm2", function ($join) {
        $join->on("pm2.post_id", "=", "posts.ID")
             ->where("pm2.meta_key", "product_name");
    })
    ->orderBy("pm1.meta_value", "desc")
    ->orderBy("pm2.meta_value", "asc")
    ->get();

In this code, we are performing two separate joins on the postmeta table, one for the visits meta key and another for the product_name meta key. Then we use the orderBy method to specify the order of sorting for each meta field.

Make sure to adjust the table alias (pm1 and pm2) and the meta key names (visits and product_name) according to your actual database schema.

With this modification, the results will be sorted by visits in descending order and then by product_name in ascending order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants