Matthew
Matthew

Reputation: 1655

Laravel Model Relationship with Where & orWhere Statement

I have the following in my controller:

            $documents = $equipment->attachments()
                ->where('attachmentCategory','=','Document')
                ->orWhere('attachmentCategory','=','Vehicle Title')
                ->get();

But while the documents with attachmentCategory that are equal to Document return fine, it proceeds to bring in ALL documents with the Vehicle Title attachmentCategory, even though if I try this statement with just the where and it being Vehicle Title it will only return one document (which is correct).

This is my relationship as defined in my function, and this has not failed me anywhere else, so I do know it's in the above controller statement, I am just putting this here just in case.

public function attachments()
{
    return $this->hasMany(EquipmentAttachment::class,'unitID','id');
}

If you could correct the statement above, that would be great. I would like it to return documents to me only if they have an attachmentCategory of Document OR Vehicle Title.

Upvotes: 0

Views: 181

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

I would like it to return documents to me only if they have an attachmentCategory of Document OR Vehicle Title.

From above i assume you need to apply filter on related collection, If it matches the given criteria then return main object like Querying Relationship Existence

$documents = $equipment->whereHas('attachments', function ($query) {
                            $query->whereIn('attachmentCategory', ['Document', 'Vehicle Title']);
                        })
                        ->get();

Upvotes: 1

DevK
DevK

Reputation: 9942

Seems like that might be a Laravel bug. I'll test it out.

This is the solution though:

$documents = $equipment->attachments()
    ->where(function ($q) {
        $q
            ->where('attachmentCategory','=','Document')
            ->orWhere('attachmentCategory','=','Vehicle Title');
    })
    ->get();

Upvotes: 1

Related Questions