使用数据透视表获取额外属性?

Noi*_*art 0 laravel laravel-5 laravel-5.7

我正在关注 Laracasts 上的多对多关系 Laravel 教程 - 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同步etc to associatetagX tagY tagZ article1` to。但是,我也希望能够选择将关联标签之一设置为“isGreenTag”。我可以在跟踪多对多关系的数据透视表中执行此操作吗?我可以添加一列“is_green_tag”吗?

这是我的Article班级关系:

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

这是我的Tag班级关系:

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

这是我对数据透视表的迁移:

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();
    });
}
Run Code Online (Sandbox Code Playgroud)

我可以添加到数据透视表迁移$table->boolean('is_green_tag')->nullable()吗?

GTC*_*ais 7

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

$table->boolean('is_green_tag')->default(0);
Run Code Online (Sandbox Code Playgroud)

然后你可以修改文章类上的关系:

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

一旦你有了一个Article对象,你就可以访问该属性:

foreach ($article->tags as $tag) {
    if ($tag->pivot->is_green_tag) {
        // some logic here
    }
}
Run Code Online (Sandbox Code Playgroud)

保存is_green_tag$tagId

$article->tags()->attach($tagId, ['is_green_tag' => 1]);
Run Code Online (Sandbox Code Playgroud)

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