【问题标题】:Laravel joining two tables column id in where clause ambiguousLaravel 在 where 子句中加入两个表列 id 不明确
【发布时间】:2021-03-17 10:47:40
【问题描述】:

我正在尝试根据公共列值在我的 Laravel 项目中加入一个表。我有两张桌子:

  1. 报告
  2. 报告数据

单个报告包含一个名为 report_data_id 的字段在某些时候会更新并包含该表中的报告数据 ID,但是,无论我使用的是 id 列还是完全单独的列,还是不同类型的加入,无论如何我都会收到以下错误:

SQLSTATE[23000]:违反完整性约束:1052 where 子句中的列 'id' 不明确

我不确定我在代码中做错了什么?

$report = DB::table('reports')
            ->where('id', $id)
            ->where('user_id', Auth::id())
            ->join('report_data', 'report_data.id', '=', 'reports.report_data_id')
            ->first();

我需要先从我的请求中选择 ID 与请求的 ID 匹配的报告,以及用户 ID 与登录用户匹配的报告,这很重要,以免得到不正确的报告。

然后我需要从report_data 表中获取报告数据,其中该表包含id,默认id 列与我的报告表中的report_data_id 列匹配。

我尝试在report_data 表中添加单独的列,但这不起作用。

我在这里做错了什么?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    试试下面的代码。使用别名,因为您的查询没有指定 id 列使用哪个别名。

    $report = DB::table('reports')
                ->where('reports.id', $id)
                ->where('reports.user_id', Auth::id())
                ->join('report_data', 'report_data.id', '=', 'reports.report_data_id')
                ->first();
    

    【讨论】:

      【解决方案2】:

      在这个查询中,report_datareports 都有,因为它们都有一个 id 列,MySql 不知道该使用哪个。指定 id 列,它将起作用。

      ->where('reports.id', $id)
      

      【讨论】:

        【解决方案3】:

        您可以写where('reports.id', $id) 来消除歧义。

        完整查询

        $report = DB::table('reports')
                    ->where('reports.id', $id)
                    ->where('user_id', Auth::id())
                    ->join('report_data', 'report_data.id', '=', 'reports.report_data_id')
                    ->first();
        

        【讨论】:

          【解决方案4】:
          $report = DB::table('reports')
                      ->where('reports.id', $id)
                      ->where('reports.user_id', Auth::id())
                      ->join('report_data', 'report_data.id', '=', 'reports.report_data_id')
                      ->first();
          

          【讨论】:

          • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
          猜你喜欢
          • 2017-07-22
          • 2014-05-03
          • 2019-04-05
          • 2021-05-30
          • 1970-01-01
          • 1970-01-01
          • 2019-09-03
          • 2020-10-13
          • 1970-01-01
          相关资源
          最近更新 更多