加入表并查找并获取指定的行 Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33038853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:28:37  来源:igfitidea点击:

join table and find and get an specified row laravel

phpmysqllaravellaravel-5eloquent

提问by Juliver Galleto

Im trying to get an specified record from a join table, my query is as below

我试图从连接表中获取指定的记录,我的查询如下

$user = Auth::user(); //current authenticated user
$user_id = $user->id; //get the current authenticated user's id
$users = DB::table('users') //join table users and table user_details base from matched id;
    ->join('user_details', 'users.id', '=', 'user_details.id')
    ->find($user->id) //find the record matched to the current authenticated user's id from the joint table records
    ->get(); //get the record
dd(var_dump($users)); //dump result

but unfortunately sadly it gives me this error

但不幸的是它给了我这个错误

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from usersinner join user_detailson users.id= user_details.idwhere id= 1 limit 1)

SQLSTATE[23000]:违反完整性约束:1052 where 子句中的列 'id' 不明确(SQL:select * from usersinternal join user_detailson users. id= user_details. idwhere id= 1 limit 1)

so i bet my query is wrong LOL! anyway, any help, ideas please?

所以我敢打赌我的查询是错误的,哈哈!无论如何,任何帮助,想法好吗?

回答by Narendrasingh Sisodia

As the error itself depicts that on which tables idshould it place condition so you need to replace your findwith wherelike as

由于错误本身描述了上表id应该放置它的条件,所以你需要更换findwhere等作为

->where("users.id",$user->id)

instead of

代替

->find($user->id)

回答by Peter Kota

You should use 'user_id' in user_details table (not only 'id'), because it doesn't know what table id belongs to in the where clause.

您应该在 user_details 表中使用 'user_id'(不仅仅是 'id'),因为它不知道 where 子句中的表 id 属于哪个。

  1. change idto user_idin your user_detailstable
  2. try this: ->join('user_details', 'users.id', '=', 'user_details.user_id')
  1. 更改iduser_id在您的user_details表中
  2. 尝试这个: ->join('user_details', 'users.id', '=', 'user_details.user_id')

If you don't want to change your db: Replace ->find($user->id)with ->where("users.id", "=", $user->id)

如果您不想更改数据库:替换->find($user->id)->where("users.id", "=", $user->id)

回答by Ali Akbar Khasheai

Try this: use where()method instead of find()method. This will work.

试试这个:使用where()方法而不是find()方法。这将起作用。