使用 pivot table 来获得额外的属性?

Use pivot table for extra attributes?

我正在关注 Laracasts 上的多对多关系 Laravel 教程 - https://laracasts.com/series/laravel-5-fundamentals/episodes/21

我对自己的挑战是,我创造了枢轴 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`。但是,我还希望能够有选择地将关联标签之一设置为 "isGreenTag"。我可以在跟踪多对多关系的枢轴 table 中执行此操作吗?我可以添加一列 "is_green_tag" 吗?

这是我的 Article class 关系:

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

这是我的 Tag class 关系:

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

这是我对枢轴的迁移 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();
    });
}

我可以添加到枢轴 table 迁移 $table->boolean('is_green_tag')->nullable() 吗?

是的,你可以给它一个默认值 0 而不是让它可以为空:

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

然后就可以修改文章class上的关系了:

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
    }
}

$tagId 节省 is_green_tag

$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