我正在阅读laravel 5.2文档以在我的Laravel应用程序中实现多对多多态关系。 我有像Blog
,Question
,Photo
等许多模型等,我想要所有的标签系统。 我创建了具有以下架构的Tag表格如何在Laravel 5.2中使用多对多多态关系
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
下面是枢轴表架构。数据透视表的名称是entity_tags
Schema::create('entity_tags', function (Blueprint $table) {
$table->increments('id');
$table->integer('tag_id')->unsigned();;
$table->integer('taggable_id')->unsigned();
$table->string('taggable_type');
$table->timestamps();
$table->index('tag_id');
$table->index('taggable_id');
$table->index('taggable_type');
});
这是Tag
模型中定义为Question
模型
public function questions()
{
return $this->belongsToMany('App\Question', 'entity_tags', 'tag_id', 'taggable_id');
}
的关系,并以下关系在Question
模型中定义
public function tags()
{
return $this->belongsToMany('App\Tag', 'entity_tags', 'taggable_id', 'tag_id');
}
现在我想定义Laravel 5.2中定义的多对多关系。
我的问题是
- 我怎么能定义它们?
- 我是否应删除多对多关系并只定义多对多关系? 如果是,那么如何管理自定义数据透视表名称?
- 此外,它是否需要后缀列名称与单词
able
是 多态关系的一部分?
我尝试了解决方案,但以下是误差,当我保存的新问题 'SQLSTATE [42S22] :未找到列:1054'where子句'中的未知列'tagz_type'(SQL:从'entity_tags'中选择'entity_type'其中'entity_id'= 4和'tagz_type'= App \ Question)' 我认为第二个参数应该是'xyz' –
还有一件事,我没有使用'xyz_id'和'xyz_type',而是使用了'entity_id'和'entity_type' –