简体   繁体   English

Laravel 5.1在其他表中查找带有project_id的项目所有者电子邮件

[英]Laravel 5.1 finding project owner email with project_id in other table

I am trying to find a users email when I know the project id. 当我知道项目ID时,我正在尝试查找用户的电子邮件。

So in my table projects for example I have a record: id: 1 user_id: 6 例如,在我的表项目中,我有一条记录:id:1 user_id:6

I know want to find the email of user 6 in my users table: for example: id: 6 email: hello@gmail.com 我知道要在我的用户表中找到用户6的电子邮件:例如:id:6电子邮件:hello@gmail.com

so as a result I want to get hello@gmail.com 所以我想得到hello@gmail.com

I've tried something like this, but doesn't seem to be working: 我已经尝试过类似的方法,但是似乎没有用:

$projectOwnerEmail = DB::table('users')
        ->select('email')
        ->where('id', '=', $input['project_id'])
        ->join('projects', 'users.id', '=', 'projects.user_id')
        ->get();

Many thanks! 非常感谢!

The query you create using the Query Builder is the following: 您使用查询生成器创建的查询如下:

SELECT email
FROM users
INNER JOIN projects ON users.id = projects.user_id
WHERE id = ?

The problem with this is that when evaluating the condition, there is no way to determine if you are trying to compare the id of the users table or the id of the projects table. 这里的问题是,评估条件的时候,没有办法确定,如果你想比较id中的users表或id的的projects表。 This results in an integrity constraint violation error: 这导致完整性约束违反错误:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous SQLSTATE [23000]:违反完整性约束:1052 where子句不明确的列“ id”

To fix this you just need to specify the table for the id column like so: 要解决此问题,您只需要为id列指定表,如下所示:

->where('projects.id', '=', $input['project_id'])

Also, using get will return a collection, which is ok because you can access the email like so $projectOwnerEmail[0]->email , but that feels overly complicated. 另外,使用get将返回一个集合,这是可以的,因为您可以像$projectOwnerEmail[0]->email这样访问$projectOwnerEmail[0]->email ,但这感觉过于复杂。 Instead you can use pluck which will return a string with the email address instead: 相反,您可以使用pluck ,它将返回带有电子邮件地址的字符串:

$projectOwnerEmail = DB::table('users')
    ->select('email')
    ->where('projects.id', '=', $input['project_id'])
    ->join('projects', 'users.id', '=', 'projects.user_id')
    ->pluck('email');

Now you have the email string stored directly in the $projectOwnerEmail variable. 现在,您已经将电子邮件字符串直接存储在$projectOwnerEmail变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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