1

when I try to run:

$alunos = DB::table('students')
    ->select('students.id','students.name','students.matricula','students.birth')
    ->join('horarios_has_students','horarios_id','=',DB::Raw($id))
    ->whereRaw('students.id = horarios_has_students.students_id')
    ->where('students.situation',1)
    ->orderBy('students.name', 'ASC')
    ->get();

And It works just fine. But if I change DB::Raw($id) for just $id, like this:

... 
->join('horarios_has_students','horarios_id','=',$id)
...

It doesn't work because in this case horarios_id is a foreign key and Laravel add quotations marks (the ones used in MySQL queries). So I get this error message:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column '3' in 'on clause' (SQL: select `students`.`id`, `students`.`name`, `students`.`matricula`, `students`.`birth` from `students` inner join `horarios_has_students` on `horarios_id` = `3` where students.id = horarios_has_students.students_id and `students\`.`situation` = 1 order by `alunos`.`name` asc) "

With DB::Raw() works because it removes the ``, so this would work just if the command was ... on `horarios_id` = 3 ... What should I do to fix this? Thanks in advance.

1
  • Put the table to join on the function, never put only "id" becase your tables can have mutiple of them: ->join('table','table_join.id,'=', table.id) Commented May 28, 2018 at 15:14

1 Answer 1

0

Use this:

$alunos = DB::table('students')
    ->select('students.id', 'students.name', 'students.matricula', 'students.birth')
    ->join('students.id', 'horarios_has_students.students_id')
    ->where('horarios_has_students.horarios_id', $id)
    ->where('students.situation', 1)
    ->orderBy('students.name', 'ASC')
    ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please give feedback on the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.