简体   繁体   中英

Laravel joining two tables column id in where clause ambiguous

I'm trying to join a table in my Laravel project based on a common column value. I have two tables:

  1. Reports
  2. Report data

A single report contains a field called report_data_id gets updated at some point and contains the report data ID from that table, however, regardless of whether I use the id column or an entirely seperate column, or different type of join, I get the following error regardless:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous

I'm not sure what I'm doing wrong here in my code?

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

I need to first select the report where the ID matches the requested ID from my request, and where the User ID matches the logged in user, this is important so not to get the incorrect report.

I then need to get the report data from the report_data table where that table contains an id , the default id column matches the report_data_id column from my reports table.

I've tried adding a separate column to my report_data table, but this doesn't work.

What am I doing wrong here?

Try the following code. Use the alias because your query doesn't specify which alias to use for id column.

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

In this query there will both be report_data and reports , since they both have an id column, MySql don't know which to use. Specify the id column and it will work.

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

You can write where('reports.id', $id) to remove ambiguity.

Full Query

$report = DB::table('reports')
            ->where('reports.id', $id)
            ->where('user_id', Auth::id())
            ->join('report_data', 'report_data.id', '=', 'reports.report_data_id')
            ->first();
$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM