Reputation: 6740
I have User
, Account
and Item
models.
Account
has many User
relations, and User
has many Account
relations. These are defined as many to many.
An Account
has many Item
relations, and I am wondering how to fetch all Item
on all Account
relations for a User
.
// User.php:
public function accounts()
{
return $this->belongsToMany( Account::class );
}
// Account.php
public function users()
{
return $this->belongsToMany( User::class );
}
// Item.php
public function account()
{
return $this->belongsTo( Account::class );
}
Any idea on how to do a call like auth()->user()->items
or auth()->user()->accounts()->items
?
Upvotes: 0
Views: 65
Reputation: 25906
You can define a direct BelongsToMany
relationship by "skipping" the accounts
table:
class User extends Model
{
public function items()
{
return $this->belongsToMany(
Item::class,
'account_user',
'user_id', 'account_id', null, 'account_id'
);
}
}
$items = auth()->user()->items;
Upvotes: 2
Reputation: 17206
If you just want a list a items with those conditions, start from the item model
$userId = auth()->id();
$items = Item::whereHas('account', function($account) use ($userId) {
$account->whereHas('users', function($user) use ($userId) {
$user->where('id','=', $userId);
});
})->get();
Upvotes: 1
Reputation: 1639
as per your relationship, you can fetch every accounts of a user with every items on each of those accounts as follows:
auth()->user()->accounts()->with('items')->get();
for the above statement to work, you need to define items
relationship on your Account
model as follows:
//Account.php
public function items()
{
return $this->hasMany( Item::class );
}
Upvotes: 2