MTVS
MTVS

Reputation: 2096

Checking for relationships between related models?

Assume A and B models are related to each others using Eloquent relations.

How should I check if an instance from A has relation with an instance from B?

For example in A hasMany B and A belongsToMany B situations I want to check if $a has relationship with $b.

I think I can check for this by accessing the relation object $a->relatedBs() but I don't know how?

Upvotes: 0

Views: 31

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

There has been PR to the framework exactly for this: https://github.com/laravel/framework/pull/4267

$b = B::find($id);

$as = A::hasIn('relationB', $b)->get();

However Taylor didn't merge it, so you need whereHas:

// to get all As related to B with some value
$as = A::whereHas('relationB', function ($q) use ($someValue) {
   $q->where('someColumn', $someValue);
})->get();

// to check if $a is related to $b
$a->relationB()->where('b_table.id', $b->getKey())->first(); // model if found or null

// or for other tha m-m relations:
$a->relationB()->find($b->getKey()); // same as above

// or something more verbose:
$a->relationB()->where('b_table.id', $b->getKey())->exists(); // bool

Upvotes: 1

danhardman
danhardman

Reputation: 621

A::has('B')->get();

As shown in the laravel docs: http://laravel.com/docs/eloquent#querying-relations

Upvotes: 0

Related Questions