Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mgyback's avatar

Help with a query

Hello, i have a query looking like this: DB::table(DB::raw('(SELECT *, MATCH(name) AGAINST('DDR5' IN BOOLEAN MODE) AS relevance FROM products) AS innerTable')) ->where('innerTable.relevance', '>', 0) ->get();

But i need to rewrite it so it starts from the products-model instead of a raw query. Any idea on how i can do this?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

You can use Laravel's Eloquent ORM to achieve the same result. Here's an example:

$products = Product::selectRaw('*, MATCH(name) AGAINST(? IN BOOLEAN MODE) AS relevance', ['DDR5'])
    ->whereRaw('MATCH(name) AGAINST(? IN BOOLEAN MODE) > 0', ['DDR5'])
    ->get();

In this example, we're using the selectRaw method to select all columns from the products table and also calculate the relevance score using MySQL's MATCH function. We're passing the search term DDR5 as a parameter to the selectRaw method.

Then, we're using the whereRaw method to filter the results based on the relevance score. We're passing the search term DDR5 as a parameter to the whereRaw method as well.

Finally, we're calling the get method to retrieve the results.

Note that you'll need to define a Product model that extends Laravel's Illuminate\Database\Eloquent\Model class and represents the products table in your database.

Please or to participate in this conversation.