search

Home  >  Q&A  >  body text

SQL Request Guide in Laravel

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粉124890778P粉124890778449 days ago537

reply all(1)I'll reply

  • P粉976737101

    P粉9767371012023-09-07 09:13:36

    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()

    reply
    0
  • Cancelreply