Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel orderByRaw() on the query builder

there is no way to make such a query(with the binding) using the Laravel query builder right now:

SELECT * FROM `posts` WHERE MATCH( `title`, `description` AGAINST( 'bar' IN BOOLEAN MODE)) ORDER BY (MATCH( 'title' AGAINST( 'bar' )) DESC;

this will order the results by relevance, If we had(which we don't now!) orderByRaw then the above query would be:

Post::whereRaw("MATCH( `title`, `description` AGAINST( ? IN BOOLEAN MODE))", array('bar'))->orderByRaw("(MATCH( 'title' AGAINST( ? )) DESC", array('bar'))->get();

I opened this issue but It didn't get anywhere: https://github.com/laravel/framework/issues/2134

any suggestion?

like image 363
Amir Avatar asked Nov 19 '13 07:11

Amir


People also ask

What is Laravel query builder?

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.

How do I use whereBetween in laravel?

The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.

Where IS NOT NULL eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

Does laravel have relationship?

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.


1 Answers

Using Eloquent you can do the following:

$match = "
    match (
        `title`,
        `description`
    ) against (
        ?
        IN BOOLEAN MODE
    )";

$against = 'bar';

$sql->whereRaw($match, array($against));
$sql->orderByRaw($match . " DESC", array($against));

The same would work with the Query Builder, but then you have to do a little rewriting.

like image 72
Ronald Hulshof Avatar answered Nov 09 '22 01:11

Ronald Hulshof