Как исправить: отношения между двумя сводными таблицами - PullRequest
1 голос
/ 17 июня 2019

Я пытаюсь построить отношения между тремя столами.Сначала у нас есть таблица "decks", которая содержит информацию о каждой колоде с id владельца.Тогда у нас есть таблица "cards", которая содержит только информацию для карт.Наконец, у меня есть две сводные таблицы, одна с именем CardsAndUsers, которая содержит id, card_id и user_id, а другая с именем CardsInDecks, которая содержит только cards_users_id и deck_id.

Проблема Iесть то, что я не знаю, как связать все это.

Я работаю с Laravel 5.8

Это структура таблиц

cards
  id
  title
  description
  cost
  type
  kingdom
  image
  health
  attack
decks
  id
  title
  description
  user_id
cards_and_users
  id
  card_id
  user_id
cards_in_decks
  card_and_user_id
  user_id

Миграция палубы

        Schema::create('decks', function (Blueprint $table) {
            $table->string('id', 255)->unique();
            $table->string('title', 255);
            $table->text('description');
            $table->string('user_id', 255);
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });


Миграция карт

        Schema::create('cards', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title', 255);;
            $table->text('description');
            $table->unsignedInteger('cost');
            $table->string('type', 255);
            $table->string('kingdom', 255);
            $table->string('image', 255);
            $table->integer('health');
            $table->integer('attack');
            $table->timestamps();
        });

Cards_and_users Миграция

        Schema::create('cards_and_users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('user_id', 255);
            $table->unsignedBigInteger('card_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('card_id')->references('id')->on('cards')->onDelete('cascade');
            $table->timestamps();
        });

cards_in_decks Миграция

        Schema::create('cards_in_decks', function (Blueprint $table) {
            $table->unsignedBigInteger('carduser_id');
            $table->string('deck_id', 255);
            $table->foreign('carduser_id')->references('id')->on('cards_and_users')->onDelete('cascade');
            $table->foreign('deck_id')->references('id')->on('decks')->onDelete('cascade');
            $table->timestamps();
        });

Card.php

{
  protected $fillable = [
    'title', 'description', 'cost', 'type', 'kingdom', 'image', 'health', 'attack'
  ];

  public function users(){
    return $this->belongsToMany(User::class, 'cards_and_users')>withPivot('card_id', 'user_id')->withTimestamps();
  }

  public function decks(){
    return $this->belongsToMany(Deck::class, 'cards_in_decks')->withPivot('carduser_id', 'deck_id')->withTimestamps();
  }
}

Deck.php

class Deck extends Model
{

  protected $primaryKey = 'id';
  public $incrementing = false;
  protected $keyType = 'string';

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

  protected $fillable = [
    'id', 'title', 'description', 'user_id',
  ];

  public function cards(){
    return $this->belongsToMany(Card::class, 'cards_in_decks')->withPivot('carduser_id', 'deck_id')->withTimestamps();
  }

  public function user(){
    return $this->belongsTo(User::class);
  }
}

Я получаю сообщение о том, что столбец cardindecks.card_id не существует (очевидно).Но я не знаю, почему Laravel ожидает его существования.

РЕДАКТИРОВАТЬ 1

После исследования я обнаружил, что с помощью метода attach() могу передать более одного пареметраотношения многих ко многим.Мне просто нужно было передать carduser_id, изменить мою таблицу cards_in_decks и добавить это поле.

Пример:

$deck = Deck::find("5d09525cad67b");
$deck->cards()->attach(1, ['carduser_id' => 3]);

Я чувствую себя очень глупо.

...