dimanche 2 décembre 2018

Use pivot table for extra attributes?

I am following the many to many relationships Laravel tutorial here on Laracasts - https://laracasts.com/series/laravel-5-fundamentals/episodes/21

My challenge to myself is, I have created the pivot table 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 runsyncetc to associatetagXtagYtagZtoarticle1`. However I also want to be able to optionally set one of the associated tags as "isGreenTag". Can I do this within the pivot table that is keeping track of the many-to-many relations? Could I add a column "is_green_color"?

Here is my Article class relationship:

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

Here is my Tag class relationship:

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

Here is my migration for the pivot table:

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();
    });
}

Can I add to the pivot table migration $table->boolean('is_green_tag')->nullable()?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2rfr9D0
via IFTTT

Aucun commentaire:

Enregistrer un commentaire