Laravel Данные запроса Lighthouse GraphQL из сводной таблицы, соединяющей три таблицы - PullRequest
0 голосов
/ 12 января 2020

В Laravel Lighthouse GraphQL, как вы можете получить информацию из промежуточной "сводной" таблицы?

Предположим, у меня есть пользователи и роли в отношении toTMany:

type User {
  roles: [Role!]! @belongsToMany
}

type Role {
  users: [User!]! @belongsToMany
}

type Query {
    user(id: ID! @eq): User @find
    role(id: ID! @eq): Role @find
}

А также предположим, что промежуточная таблица User_Role содержит столбцы «create_at» и «tag_id».
Как бы я go собирался включить «made_at» в мой запрос?
Как бы получить тег, который tag_id относится к?

1 Ответ

1 голос
/ 12 января 2020

Я обнаружил, что вы можете сделать это следующим образом:

Сначала убедитесь, что отношение в модели User вызывает ->withPivot('created_at', 'tag_id'):

class User extends Model {
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(\App\Models\Role::class, 'User_Role')
                    ->using(User_Role::class) // only needed to retrieve the tag from the tag_id
                    ->withPivot('created_at', 'tag_id');
    } 
}

Создать класс для промежуточной таблицы, которая расширяется Pivot:

class User_Role extends Pivot
{
    public function tag(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Tag::class, 'tag_id');
    }
}

Теперь измените код GraphQL следующим образом:

type User {
    id: ID!
    roles: [Role!] @belongsToMany
}

type Role {
    id: ID!
    pivot: UserRolePivot # this is where the magic happens
}

type UserRolePivot {
    created_at: Date!
    tag: Tag! @belongsTo
}

type Tag {
    id: ID!
    name: String!
}

И теперь вы можете делать запрос следующим образом:

{
  users {
    id
    roles {
      id
      pivot {
        created_at
        tag {
          id
          name
        }
      }
    }
  }
}
...