Mateusz Kaleta
Mateusz Kaleta

Reputation: 137

Laravel query on relation table

I have problem with query laravel table.

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!

Upvotes: 1

Views: 4715

Answers (3)

Mateusz Drost
Mateusz Drost

Reputation: 1191

If you want find user whos attachments met specific constraints then use whereHas method

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. Even fancy 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

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();

Upvotes: 5

Amit Gupta
Amit Gupta

Reputation: 17688

You can try it with combination of whereHas and with methods as:

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

Upvotes: 0

Mateusz Drost
Mateusz Drost

Reputation: 1191

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();

Upvotes: 0

Related Questions