1
votes

I am still getting my head around laravel eloquent. I would like to write the following query in eloquent

SELECT * FROM tableA where id = $variableID AND grade_id = $gradeID

I tried the following in eloquent:

$totalGreen = DB::select('SELECT * FROM tableA WHERE id = ? AND grade_id = ?',[$visitdetail->id],[1]);

but I get this error:

SQLSTATE[HY093]: Invalid parameter number (SQL: SELECT * FROM tableA WHERE id = 5 AND grade_id = ?)

I went through the laravel document, but didn't really find anything exclusively answering my question. Please help

2

2 Answers

1
votes

Change your code like this:

$totalGreen = DB::select('SELECT * FROM tableA WHERE id = ? AND grade_id = ?',[$visitdetail->id, 1]);

or if want to use eloquent you can write like this:

$totalGreen = YourModel::where(['id'=> $visitdetail->id, 'grade_id'=>$gradeID])->get();
1
votes

You need to have both the params in the same array (the second parameter of the select query):

$totalGreen = DB::select(
    'SELECT * FROM tableA WHERE id = ? AND grade_id = ?',
    [$visitdetail->id, 1]
)->get();

You could also use the query builder instead of writing raw SQL:

$totalGreen = DB::table('tableA')
    ->where('id', $visitdetail->id)
    ->where('grade_id', 1);
    ->get();