【问题标题】:Laravel DB::raw returning - SQLSTATE[42000]: Syntax error or access violationLaravel DB::raw 返回 - SQLSTATE [42000]:语法错误或访问冲突
【发布时间】:2020-01-13 21:05:01
【问题描述】:

为什么会出现此错误? 当我在 phpMyAdmin 中运行 SQL 时,它运行良好。

SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '' 附近使用正确的语法(SQL:从 active = true 和birthyear != 0000 且不存在的用户中选择 id(从 user.id 的 agestats 中选择 id = agestats.user_id 和 agestats.year = 2020-01-13)

SQL:

select id
from users
where active = true
  and birthyear != 0000
  and not exists (
    select 1
    from agestats
    where users.id = agestats.user_id
      and agestats.year = 2020
  )

还有 Laravel 代码:

$membersToInsert = DB::select(DB::raw(
  'select id
  from users
  where active = true
    and birthyear != 0000
    and not exists (
      select id
      from agestats
      where users.id = agestats.user_id
        and agestats.year = ' . date('Y-m-d')
));

【问题讨论】:

  • 1.换行和缩进是你的朋友,尤其是当你要求人们阅读你的代码时。 2. date('Y-m-d') 将是 2020-01-13,而不是 2020。 3. 日期字符串需要加引号。 4. 我介绍的换行符会使错误消息更加相关。
  • 哎呀,我应该亲眼看到的。我非常确定代码之前一直在工作。但是当然它不可能做到这一点。谢谢!也感谢你提醒我正确的写作。如果有更多的帖子,我会更好。再次感谢您!

标签: php mysql laravel


【解决方案1】:

date('Y-m-d') 将为您提供当前日期,例如2020-01-13,因此只需获取2020,然后使用date('Y')。我希望这对您的情况有所帮助

【讨论】:

  • 完美运行!谢谢!
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 2017-07-31
  • 2017-10-29
  • 2019-06-06
  • 2015-09-20
  • 2015-10-12
  • 2018-05-31
  • 1970-01-01
相关资源
最近更新 更多