newbie_cat
newbie_cat

Reputation: 25

How do I convert a similar MySQL query to Laravel Eloquent?

SELECT * FROM `books` WHERE books.type = 'rare' AND books.band - $value < $result

That's how I think it should be

$books= DB::table('books')
                        ->where('type ','=', 'rare')
                        ->whereRaw('band - $value < $result')   // Syntax error

I don't understand how to work with dynamic variables here.

Upvotes: 0

Views: 68

Answers (4)

Ali Raza
Ali Raza

Reputation: 192

Always use Eloquent with laravel.

$books = Books::where('type','rare')->whereRaw("band - $value < $result")->get();

Upvotes: 0

Inderpreet Singh
Inderpreet Singh

Reputation: 351

Try like this:

$books= DB::table('books')
       ->where('type ','=', 'rare')
       ->whereRaw(\DB::raw("band - $value < $result"))
       ->get();

Upvotes: 0

Thai Nguyen Hung
Thai Nguyen Hung

Reputation: 1212

Please try it:

$books= DB::table('books')
            ->where('type ', 'rare')
            ->whereRaw('band - ? < ?', [$value, $result])
            ->get();

Upvotes: 1

OMR
OMR

Reputation: 12188

try use parenthesis, it's simple:

 $books= DB::table('books')
            ->where('type ','=', 'rare')
            ->whereRaw("band - {$value} < {$result}")->get();

you can do it using binding also:

 $books= DB::table('books')
            ->where('type ','=', 'rare')
            ->whereRaw("band - ? < ?",[$value,$result])->get();

Upvotes: 0

Related Questions