【问题标题】:Laravel 5.4 subquery in where condition?Laravel 5.4 子查询在哪里条件?
【发布时间】:2017-07-11 09:45:14
【问题描述】:

我想在条件和子查询中的条件中编写子查询,检查父查询字段。

如下,

$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
            $query->select('award_user.user_id')
                    ->from('award_user')
                    ->where('award_user.user_id', 'users.id')
                    ->where('award_user.award_id', $request->award_id);
        });

查询工作正常,但是

 ->where('award_user.user_id', 'users.id')

这一行,users.id 不是从父查询中获取的。如果我手动输入数字,那么它工作正常。

我的查询有什么问题..你能建议一下吗?

【问题讨论】:

  • 奖励ID没有问题,但users.id有问题
  • 您应该尝试通过添加->toSql() 来获取sql 格式的查询,然后在phpMyadmin 或Mysql 查询浏览器中手动运行!

标签: php mysql laravel subquery


【解决方案1】:

使用whereRaw 而不是where

$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
            $query->select('award_user.user_id')
                    ->from('award_user')
                    ->whereRaw('award_user.user_id', 'users.id')
                    ->whereRaw('award_user.award_id = '.$request->award_id);
        });

【讨论】:

  • 现在父用户 ID 正在工作,但第二个 whereRaw 没有应用
  • @NaseehaSahla, ->whereRaw('award_user.award_id = '.$request->award_id); 将其用作第二个 whereRaw 值。
  • 在第二个 whereRaw 不工作,但在哪里工作而不是在第二个不改变仍然不工作,而不是让我知道
猜你喜欢
  • 2019-11-27
  • 2018-11-29
  • 2015-07-29
  • 2017-03-23
  • 1970-01-01
  • 2016-07-30
  • 2017-06-16
  • 2017-12-04
  • 2019-04-27
相关资源
最近更新 更多