SQL Request Guide in Laravel
P粉124890778
P粉124890778 2023-09-06 19:29:24
0
1
471

I have a request for a job in phpMyAdmin

SELECT DISTINCT id, name, articul FROM products WHERE category_id=40 order by articul;

How do I perform this request in the correct format using the query builder in Laravel? What should the model's approach be?

First, I tried using the following code:

$products = Product::orderBy('aerucul')
    ->select('articul', 'id', 'name')
    ->distinct()
    ->where('category_id', 40)
    ->get();

But I get duplicate results.

If I try to use the following code, the result is the same:

$products = DB::select("SELECT DISTINCT id, name, articul FROM products WHERE category_id='40' order by articul");

P粉124890778
P粉124890778

reply all(1)
P粉976737101

Try to use DB::table() method

$products = DB::table('products')
    ->select('id', 'name', 'articul')
    ->distinct()
    ->where('category_id', '=', 40)
    ->orderBy('articul')
    ->get();

If you only want to get a product, instead of using ->get(), use first()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!