2016-02-28 78 views
5

我正在閱讀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是 多態關係的一部分?

回答

4
  • 使用return $這個 - > morphToMany(),而不是belongsToMany,並在標籤模式,寫3種方法,返回$這個 - > morphedByMany()的反向關係。

  • 您只需要多態定義,不需要多對多的普通定義。數據透視表的名稱在默認約定的末尾帶有'able',但您可以將其命名爲任何您想要的名稱。不,你不必在最後有一個'能夠'的詞,它只是一種方法來定義它是更普遍的東西,你可以將它命名爲任何你想要的。

命名是基於Laravel的一些默認約定。

更新:

您有以下透視表的模式:

Schema::create('entity_tags', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('tag_id')->unsigned();; 
     $table->integer('entity_id')->unsigned(); 
     $table->string('entity_type'); 
     $table->timestamps(); 
     $table->index('tag_id'); 
     $table->index('entity_id'); 
     $table->index('entity_type'); 
}); 

和標籤表:

Schema::create('tags', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->string('name'); 
    $table->string('slug')->unique(); 
    $table->timestamps(); 
}); 

所以,你想創建一個博客,視頻和問題的關係表/型號:

標籤。PHP型號:

public function questions() 
{ 
    return $this->morphedByMany('App\Question', 'entity', 'entity_tags'); 
} 

public function blogs() 
{ 
    return $this->morphedByMany('App\Blog', 'entity', 'entity_tags'); 
} 

public function videos() 
{ 
    return $this->morphedByMany('App\Video', 'entity', 'entity_tags'); 
} 

Question.php/blog.php的/ Video.php

public function tags() 
{ 
    return $this->morphToMany('App\Tag', 'entity', 'entity_tags'); 
} 
+0

我嘗試瞭解決方案,但以下是誤差,當我保存的新問題 'SQLSTATE [42S22] :未找到列:1054'where子句'中的未知列'tagz_type'(SQL:從'entity_tags'中選擇'entity_type'其中'entity_id'= 4和'tagz_type'= App \ Question)' 我認爲第二個參數應該是'xyz' –

+0

還有一件事,我沒有使用'xyz_id'和'xyz_type',而是使用了'entity_id'和'entity_type' –