Home » Php » How to order by where in fields in Laravel

How to order by where in fields in Laravel

Posted by: admin October 29, 2017 Leave a comment

Questions:

I did some calculate in a view table for products in MYSQL, so I list these id for product reference id.

$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');

And I want to get the product from those reference id.

$products = Product::whereIn('id', $rederenceIds);

The product content is correct, but the order is wrong, how to load product order by reference id, I know I can do it in MySQL by using ORDER BY FIELD(id,' . $fields . '), but I want to find out Laravel way, and hope not use ORDER BY FIELD command because it seems waste to much database efficiency.

Answers:

You will have to inject some raw sql, but it’s not a nightmare:

$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
$referenceIdsStr = implode(',', $referenceIds);
$products = Product::whereIn('id', $rederenceIds)->orderByRaw(DB::raw("FIELD(product_id, $referenceIdsStr)"))->get()->all();

Questions:
Answers:

Not sure if I understand this entirely, but if you want the products ordered, you should use

$referenceIds = viewTable::lists('product_id');

$ordered_products = Product::whereIn('id', $rederenceIds)->orderBy('id', 'DESC')->get();

Questions:
Answers:

If the key is primay key (I think in this question it is …), you can try this:

$products = Product::whereIn('id', $rederenceIds)->get();
$products = array_replace(array_flip($rederenceIds), $products->getDictionary());

The result is Array, not Collection.

I don’t know whether it has an efficiency problem, but order by field has other problems. For example, order by field is not supported by sqlite so it doesn’t work in testing with in-memory database.