【问题标题】:Get all relations through manyToMany relation通过manyToMany关系获取所有关系
【发布时间】:2020-01-07 13:55:31
【问题描述】:

我有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 之类的电话吗?

【问题讨论】:

    标签: laravel eloquent eloquent-relationship


    【解决方案1】:

    根据您的关系,您可以获取用户的每个帐户以及每个帐户上的每个项目,如下所示:

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

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

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

    【讨论】:

      【解决方案2】:

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

      $userId = auth()->id();
      $items = Item::whereHas('account', function($account) use ($userId) {
          $account->whereHas('users', function($user) use ($userId) {
              $user->where('id','=', $userId);
          });
      })->get();
      

      【讨论】:

        【解决方案3】:

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

        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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-10
          • 1970-01-01
          • 2015-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-01
          • 2021-07-31
          相关资源
          最近更新 更多