MySql Query error in Laravel

I am using laravel 5.4. When trying to run

select * from `users` inner join `addprojects` on `users`.`emp_id` = `addprojects`.`emp_id` where `emp_id` = $emp_id)"

It produces:

"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'emp_id' in where clause is ambiguous (SQL: select * from users inner join addprojects on users.emp_id = addprojects.emp_id where emp_id = $emp_id)"

$emp_id= Auth::user()->emp_id;
$projects_for_emp = DB::table('users')->join('addprojects', 'users.emp_id', '=', 'addprojects.emp_id')->where('emp_id', '$emp_id')->get();

Upvotes: 1

Views: 64

Answers (3)

rubyshine72
rubyshine72

Reputation: 132

Because both users and addprojects tables have same named field "emp_id". You can change your code like following.

$emp_id= Auth::user()->emp_id;
$projects_for_emp = DB::table('users')
    ->join('addprojects', 'users.emp_id', '=', 'addprojects.emp_id')
    ->where('users.emp_id', $emp_id)
    ->get();

Upvotes: 1

Matiur Rahman Mozumdar
Matiur Rahman Mozumdar

Reputation: 441

emp_id in both tables , so can use users.emp_id or addprojects.emp_id

->where('users.emp_id', '=', $emp_id)

Upvotes: 3

Marek Maszay
Marek Maszay

Reputation: 1547

You have specified column name which exists in both tables, so use users.emp_id or addprojects.emp_id doesn't matter which one

Example:

$emp_id= Auth::user()->emp_id;
$projects_for_emp = DB::table('users')
   ->join('addprojects', 'users.emp_id', '=', 'addprojects.emp_id')
   ->where('users.emp_id', '$emp_id')
   ->get();

Upvotes: 2

Related Questions