我搞不太清楚这里面的自定义 'foreign_key', 'local_key'
例如:
数据表结果:
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('subject');
$table->timestamps();
}
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
}
Schema::create('article_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('article_id')->unsigned()->index();
$table->integer('tag_id')->unsigned()->index();
$table->foreign('article_id')
->references('id')
->on('articles')
->onDelete('cascade');
$table->foreign('tag_id')
->references('id')
->on('article_tags')
->onDelete('cascade');
});
Model代码如下:
class Article extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class);
//上面这个:belongsToMany(Tag:class,foreignKey,otherKey)
//foreignKey:我想自定义这个外键,我是写`article_id`还是应该写`tag_id`??
//otherKey:我想自定义这个外键,我是写article表中的主键id还是应该写tag表中的主键id??
}
}
class ArticleTag extends Model
{
public function articles()
{
return $this->belongsToMany(Article::class,'article_id');
//上面这个:belongsToMany(Tag:class,foreignKey,otherKey)
//foreignKey:我想自定义这个外键,我是写article_id还是应该写tag_id??
//otherKey:我想自定义这个外键,我是写article表中的主键id还是应该写tag表中的主键id??
}
}