加入表并查找并获取指定的行 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
join table and find and get an specified row laravel
提问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
users
inner joinuser_details
onusers
.id
=user_details
.id
whereid
= 1 limit 1)
SQLSTATE[23000]:违反完整性约束:1052 where 子句中的列 'id' 不明确(SQL:select * from
users
internal joinuser_details
onusers
.id
=user_details
.id
whereid
= 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 id
should it place condition so you need to replace your find
with where
like as
由于错误本身描述了上表id
应该放置它的条件,所以你需要更换find
与where
等作为
->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 属于哪个。
- change
id
touser_id
in youruser_details
table - try this:
->join('user_details', 'users.id', '=', 'user_details.user_id')
- 更改
id
为user_id
在您的user_details
表中 - 尝试这个:
->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()
方法。这将起作用。