Использовать сводную таблицу для дополнительных атрибутов? - PullRequest
0 голосов
/ 03 декабря 2018

Я следую учебнику Laravel по многим и многим отношениям здесь, на Laracasts - https://laracasts.com/series/laravel-5-fundamentals/episodes/21

Моя задача состоит в том, чтобы я создал сводную таблицу article_tag) to keep track of the many to many relations. Articles can have many tags, and tags can have many articles. So I can run sync etc to associate tagX tagY Tagz to article1`.Однако я также хочу иметь возможность установить один из связанных тегов как «isGreenTag».Могу ли я сделать это в сводной таблице, которая отслеживает отношения «многие ко многим»?Могу ли я добавить столбец "is_green_tag"?

Вот мои Article классовые отношения:

class Article extends Model {
   public function tags() {
      return $this->belongsToMany('App\Tag')->withTimestamps();
   }
}

Вот мои Tag классовые отношения:

class Tag extends Model {
   public function articles() {
      return $this->belongsToMany('App\Articles');
   }
}

Вот моя миграция для сводной таблицы:

public function up() {
    Schema.create('article_tag', function(Blueprint $table) {
        $table->integer('article_id')->unsigned()->index();
        $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');

        $table->integer('tag_id')->unsigned()->index();
        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');

        $table->timestamps();
    });
}

Могу ли я добавить в сводную таблицу миграцию $table->boolean('is_green_tag')->nullable()?

1 Ответ

0 голосов
/ 03 декабря 2018

Да, вы можете, вы можете присвоить ему значение по умолчанию 0 вместо того, чтобы сделать его обнуляемым:

$table->boolean('is_green_tag')->default(0);

А затем вы можете изменить отношение в классе Article:

public function tags() {
    return $this->belongsToMany('App\Tag')->withPivot(['is_green_tag'])->withTimestamps();
}

Если у вас есть объект Article, вы можете получить доступ к этому свойству:

foreach ($article->tags as $tag) {
    if ($tag->pivot->is_green_tag) {
        // some logic here
    }
}

Чтобы сохранить is_green_tag для $tagId:

$article->tags()->attach($tagId, ['is_green_tag' => 1]);

Документы Laravel:
https://laravel.com/docs/5.7/eloquent-relationships#many-to-many https://laravel.com/docs/5.7/eloquent-relationships#updating-many-to-many-relationships

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...