简体   繁体   English

Laravel关系表查询

[英]Laravel query on relation table

I have problem with query laravel table. 我在查询laravel表时遇到问题。

I have relation like: each user have attachment, and attachment belongs to user. 我有这样的关系:每个用户都有附件,并且附件属于用户。 I wrote relation in model. 我在模型中写了关系。

My question is: how make query if I want to return user with relation attachment but for attachment where level = user level? 我的问题是:如果要返回具有关系附件的用户,但要返回级别=用户级别的附件,如何进行查询? Even if I make whereHas it's return me all attachment for user. 即使我在哪里拥有它也将所有附件退还给用户。 Please help! 请帮忙!

If you want find user whos attachments met specific constraints then use whereHas method 如果要查找附件符合特定限制的用户,请使用whereHas方法

UserModel::whereHas('attachments', function ($attachmentQuery) {
    $attachmentQuery->where('level', 'profile_level');
})->get();

If you want from already queried model get specific attachments then write 如果要从已经查询的模型中获取特定附件,请编写

$userModel->attachments()->where('level', 'profile_level')->get();

It is impossible to query both UserModel and AttachementModel in single query, it must be at least two queries. 不能在单个查询中同时查询UserModel和AttachementModel,它必须至少是两个查询。 Even fancy UserModel::with('attachments')->get(); 甚至是花哨的UserModel::with('attachments')->get(); , which returns user with all attachments, do internally two queries. ,它向用户返回所有附件,在内部执行两个查询。

Edit: 编辑:

I noticed that you can define relation constraints within with method 我注意到,你可以定义关系的约束范围内with方法

UserModel::with(['attachments' => function ($attachmentQuery) {
    $attachmentQuery->where('level', 'profile_level');
}])->get();

So if you want find user whos attachments met specific constraints and eager load that attachments then you can do 因此,如果您要查找附件满足特定约束的用户并渴望加载附件,则可以

$queryAttachments = function ($attachmentQuery) {
    $attachmentQuery->where('level', 'profile_level');
};

UserModel::whereHas('attachments', $queryAttachments)
->with(['attachments' => $queryAttachments])->get();

When you query model relations you write something like 当查询模型关系时,您会写类似

$attachments = $userModel->attachments;

which is a shortcut for 这是

$attachments = $userModel->attachments()->get();

so you can write 所以你可以写

$attachments = $userModel->attachments()->where('level', 'user')->get();

You can try it with combination of whereHas and with methods as: 您可以将whereHas和以下方法结合with

Profile::whereHas('attachments', function ($q) {
        $q->where('level', 'user');
    })
    ->with(['attachments', function ($q) {
        $q->where('level', 'user');
    }])
    ->get();

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

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