rebellion
rebellion

Reputation: 6740

Get all relations through manyToMany relation

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

Answers (3)

Jonas Staudenmeir
Jonas Staudenmeir

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

N69S
N69S

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

Pusparaj
Pusparaj

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

Related Questions