【问题标题】:Laravel 5.6 Custom Query Build showing empty resultLaravel 5.6 自定义查询构建显示空结果
【发布时间】:2018-11-01 22:05:39
【问题描述】:

没有错误,只是一个空结果。我试图弄清楚为什么模型中的这个查询显示一个空集合。

Mysql Workbench 查询:

select
    u.`name`, u.email, ual.admin, a.account_name
from
    users as u
    join users_account_link as ual on u.id = ual.user_id and u.account_id_in_use = ual.account_id
    join accounts a on ual.account_id = a.id
where
    u.sub = 'ABCDE';

吐出包含所需结果集的一行。

在 Laravel 查询构建器中重新创建:

$settings = DB::table('users as u')
            ->join('users_account_link as ual', function ($join) {
                  $join->on('u.id', '=', 'ual.user_id')
                       ->where('u.account_id_in_use', '=', 'ual.account_id');
                  })
            ->join('accounts as a', 'ual.account_id', '=', 'a.id')
            ->select('u.name as user_name', 'u.email as user_email', 'ual.admin as admin_check', 'a.account_name')
            ->where('u.sub',auth()->user()->sub)
            ->get();

dd($settings);

提供一个空集合。我已经完成了许多效果很好的自定义查询,但是我缩小结果集的问题是join users_account_link as ual on u.id = ual.user_id and u.account_id_in_use = ual.account_id 的附加条件,并尝试将此条件移至仍提供空结果的 where 子句。

【问题讨论】:

    标签: laravel-5.6 laravel-query-builder


    【解决方案1】:

    'u.account_id_in_use', '=', 'ual.account_id' 都是整数,但是将 u.account_id_in_use 替换为硬编码整数,例如2 将返回结果。因此,Laravel 似乎对该字段存在问题,并将 where-> 替换为 whereRaw 现在返回所需的结果。

    对于遇到类似问题的任何人,请尝试用硬编码值替换字段以隔离问题,并在可能的情况下考虑使用 raw 来解决问题。

    希望这对有需要的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2017-10-12
      • 2021-08-20
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多