Laravel Lighthouse GraphQL переименована в мутацию отношений - PullRequest
1 голос
/ 14 января 2020

У меня возникла проблема с обновлением переименованного отношения с помощью запроса graphQL.

Вот связанные схемы и Laravel модели:

Laravel Модели

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Lead extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    // protected $fillable = [
    //     'lead_type_id',
    // ];

    protected $guarded = [];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        //
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        // 'created_at' => 'timestamp',
        // 'updated_at' => 'timestamp'
    ];

    /**
     * Get the LeadActions for the Lead.
     */
    public function leadActions()
    {
        return $this->hasMany(\App\Models\LeadAction::class);
    }

    /**
     * Get the clients for the Lead.
     */
    public function clients(): BelongsToMany
    {
        return $this->belongsToMany(Client::class);
    }

    /**
     * Get the LeadType for the Lead.
     */
    public function leadType(): BelongsTo
    {
        return $this->belongsTo(\App\Models\LeadType::class, 'lead_type_id');
    }
}

?>

<?php

namespace App\Models;

use App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class LeadType extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        //
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'name' => 'string',
        'created_at' => 'timestamp',
        'updated_at' => 'timestamp'
    ];

    /**
     * Get the Leads for the LeadType.
     */
    public function leads(): HasMany
    {
        return $this->hasMany(Models\Lead::class);
    }

}
?>

Схема GraphQl

type Lead {
   id: ID!
   lead_type: LeadType @belongsTo(relation: "leadType")
   clients: [Client!]! @belongsToMany
   created_at: DateTime!
   updated_at: DateTime!
}
input UpdateLeadInput {
   id: ID!
   clients: UpdateClientsRelation
   lead_type: UpdateLeadTypeRelation
}
input UpdateLeadTypeRelation {
   create: CreateLeadTypeInput
   connect: ID
   update: UpdateLeadTypeInput
   upsert: UpsertLeadTypeInput
   delete: ID
   disconnect: ID
}

Используя следующий запрос graphQl, я получаю ошибку SQL для отсутствующего столбца lead_type: Запрос

mutation UpdateLead {
  updateLead(input: {id: 1, lead_type: {connect: 1}}) {
    id
    clients {
      id
      name
    }
    lead_type {
      id
      name
    }
  }
}

SQL Ошибка

Column not found: 1054 Unknown column 'lead_type' in 'field list' (SQL: update `leads` set `lead_type` = {\"connect\":\"1\"}, `leads`.`updated_at` = 2020-01-14 17:11:17 where `id` = 1

Я следовал соглашению об именовании Laravel и назвал столбец lead_type_id в таблице отведений. Если я удаляю переименование отношения lead_type в leadType, я могу успешно запустить мутацию обновления, но я не могу понять, как заставить его использовать правильное имя для столбца (lead_type_id), сохраняя при этом переименованное отношение.

Любая помощь очень ценится.

Большое спасибо

1 Ответ

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

Вы пробовали @rename директиву? Я имею в виду, что вы должны использовать его на lead_type в вашем UpdateLeadInput, потому что маяк ищет отношение с именем lead_type, и, поскольку оно не определено, предполагается, что lead_type является аргументом.

Либо переименуйте ваши отношения в моделях, например:

class Lead extends Model
{
    public function lead_actions()
    {
        return $this->hasMany(\App\Models\LeadAction::class);
    }

    public function lead_type(): BelongsTo
    {
        return $this->belongsTo(\App\Models\LeadType::class, 'lead_type_id');
    }
}

ИЛИ

используйте директиву @rename (я не пробовал, но я имею в виду, что она работает так):

input UpdateLeadInput {
   id: ID!
   clients: UpdateClientsRelation
   lead_type: UpdateLeadTypeRelation @rename(attribute: "leadType")
}
...