具有连接和多个where的Laravel查询

具有连接和多个where的Laravel查询,laravel,eloquent,Laravel,Eloquent,我正在尝试执行此查询: select * FROM users left join emails on users.id = emails.user_id WHERE users.username = 'firstuser' and emails.emailType = 'Primary'; 这就是我所拥有的,但它给了我一个错误: $user = User::where('username','firstuser')->with('emails')

我正在尝试执行此查询:

select
    *
FROM
    users
    left join emails on users.id = emails.user_id
WHERE
    users.username = 'firstuser'
    and emails.emailType = 'Primary';
这就是我所拥有的,但它给了我一个错误:

$user = User::where('username','firstuser')->with('emails')
                                          ->where('emailType','Primary')
                                          ->get();
该消息表示未进行连接:

Column not found: 1054 Unknown column 'emailType' in 'where clause' (SQL: select * from `users` where `username` = firstuser and `emailType` = Primary)
另外,在我的User.php模型文件中,有一个函数emails():

在我的Email.php模型中,我有一个user()函数


我尝试了很多组合,但无法同时满足两种条件。我想做一个查询,而不是两个查询(获取用户id,然后查询带有用户id的电子邮件),提前感谢所有帮助

您需要在调用
with()
时为
电子邮件的
关系指定
位置,否则,Eloquent会认为您试图在
用户
表中查找
emailType
字段

$user = User::with(['emails' => function($query){
    $query->where('emailType','Primary');    
}])->where('username','first user')
->get();

基于上面的评论,我得到了这个工作。但是,正如我在模型中定义的关系一样,这不是一个非常优雅的解决方案,但是连接绕过了所有这些,从而强制连接。这就是成功的原因

$user = User::join('emails', 'users.id', '=', 'emails.user_id')
                    ->where('emailType','=','Primary')
                    ->where('username',$username)
                    ->get();

如果在您想要查询模型时,模型中的关系不习惯于联接表,那么在模型中定义这些关系有什么意义?也许我遗漏了什么。

你需要加入
或者是
的组合。你到底期望什么结果?顺便说一句,with
with
不连接表,这就是为什么会出现错误。我尝试了这个,但没有成功。with()将不接受闭包作为参数,并且错误为预期字符串,但获取对象。请尝试将数组传递给
,其中()。。。很抱歉,花了这么长时间才选择它作为正确答案。
$user = User::with(['emails' => function($query){
    $query->where('emailType','Primary');    
}])->where('username','first user')
->get();
$user = User::join('emails', 'users.id', '=', 'emails.user_id')
                    ->where('emailType','=','Primary')
                    ->where('username',$username)
                    ->get();