CacheMoneyPlaya
CacheMoneyPlaya

Reputation: 143

how to filter within a with operator laravel

I have a group of accounts being returned, and each account has a number of relations to it (accounts related to other accounts). The following:

return AccountGroup::with(['account.relationships'])

Returns accounts with the other accounts that are related to it, the data will then look like this:

0: {accountId: 37868, name: "Random", ...}
accountId: 37868"
irdNumber: "72038410"
name: "Random"
relationships: [{relationshipId: 16851, loginId: 506, accountId: 37868, statusId: 1, groupId: 2},…]
0: {relationshipId: 16851, accountId: 37868, statusId: 1}
accountId: 37868
relationshipId: 16851
statusId: 1
1: {relationshipId: 16871, accountId: 37868, statusId: 1}

Now I want to return those relationships that have a relationship account id = accountid, i.e. where accountId = relationship.accountId

How would i go about doing this? I have read up about whereColumn but not sure if that's appropriate...

Relationships is a callable in the account model:

public function relationships()
{
    return $this->hasMany('\App\Entities\Security\Relationship\Relationship', 'accountId');
}

This then returns an array of relationships against the account in question, I want to filter out the ones that dont have a relationship.accountId = accountId

Upvotes: 0

Views: 143

Answers (2)

gbalduzzi
gbalduzzi

Reputation: 10166

You can filter the relationships loaded using with using an array syntax:

return AccountGroup::with(['account.relationships' => function ($query) {
   // Filter `account.relationships` according to your needs
   $query->where('accountId', ...);
}])

More info here: https://laravel.com/docs/master/eloquent-relationships#constraining-eager-loads


Another approach would be to define a custom relationship in the AccountGroup model for this specific need:

In your AccountGroup model:

public function relationships()
{
    return $this->hasMany('\App\Entities\Security\Relationship\Relationship', 'accountId', 'accountId');
}

Then:

return AccountGroup::with(['relationships'])

Upvotes: 1

Brian Thompson
Brian Thompson

Reputation: 14355

I believe what you're looking for is

whereHas('relationship', function($query) {
    // filter
})

https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence

Upvotes: 1

Related Questions