通过多对多关系获取所有关系

时间:2020-01-07 13:55:31

标签: laravel eloquent eloquent-relationship

我有UserAccountItem模型。

Account具有许多User关系,并且User具有许多Account关系。这些被定义为多对多。

一个Account有许多Item关系,而我想知道如何为Item获取所有Account关系中的所有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 );
}

关于如何拨打auth()->user()->itemsauth()->user()->accounts()->items之类的电话的任何想法吗?

3 个答案:

答案 0 :(得分:2)

根据您的关系,您可以按以下方式获取用户的每个帐户以及每个帐户中的每个项目:

auth()->user()->accounts()->with('items')->get();

要使上述语句生效,您需要在items模型上定义Account关系,如下所示:

//Account.php
public function items()
{
  return $this->hasMany( Item::class );
}

答案 1 :(得分:1)

您可以通过“跳过” BelongsToMany表来定义直接的accounts关系:

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;

答案 2 :(得分:1)

如果您只想列出具有这些条件的项目,请从项目模型开始

=INT(43811.1234*24)/24