【问题标题】:Laravel Query Builder doesn't identify variable as integer and adds quotation marksLaravel Query Builder 不将变量识别为整数并添加引号
【发布时间】:2018-11-07 04:54:41
【问题描述】:

当我尝试运行时:

$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();

而且它工作得很好。但是,如果我将 DB::Raw($id) 更改为 $id, 像这样:

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

它不起作用,因为在这种情况下 horarios_id 是一个外键,而 Laravel 添加了引号(在 MySQL 查询中使用的引号)。所以我收到了这个错误信息:

“SQLSTATE[42S22]:未找到列:1054 'on 子句'中的未知列 '3'(SQL:选择 `students`.`id`、`students`.`name`、`students`.`matricula `, `students`.`birth` from `students` 内部连接 ​​`horarios_has_students` on `horarios_id` = `3` where students.id = horarios_has_students.students_id 和 `students\`.`situation` = 1 order by `alunos` .`name` asc) "

使用 DB::Raw() 可以工作,因为它删除了 ``,所以只要命令是...... 在 `horarios_id` = 3 ... 我应该怎么做才能解决这个问题?提前致谢。

【问题讨论】:

  • 把表加入函数,永远不要只放“id”,因为你的表可以有多个:->join('table','table_join.id,'=', table.id)

标签: php mysql laravel laravel-query-builder


【解决方案1】:

使用这个:

$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();

【讨论】:

  • 您能否就答案提供反馈?
猜你喜欢
  • 2020-09-01
  • 2016-12-13
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多