我有這樣的設置。Laravel:多對多關係
文檔模型
public function plates()
{
return $this->belongsToMany('App\Models\Plate')->withTimestamps();
}
板模式
public function documents()
{
return $this->belongsToMany('App\Models\Document')->withTimestamps();
}
和數據透視表這樣
public function up()
{
Schema::create('document_plate', function (Blueprint $table) {
$table->integer('plate_id')->unsigned()->index();
$table->integer('document_id')->unsigned()->index();
$table->primary(['plate_id', 'document_id']);
$table->timestamps();
});
}
現在我明白了這個關係爲多對多其中m EANS我可以分配很多plate
ID的許多document
ID的權利?
這是我一直在玩的東西。
$plates = [
'plate_id_1' => 1,
'plate_id_2' => 2,
'plate_id_3' => 3,
];
$docs = [
'recipe_id' => 1,
'procedure_id' => 2,
];
// attach many docs to plates
$plate = Plate::findMany($plates);
$doc = Document::findMany($docs);
$plate->documents()->attach($doc->id);
我想要的是:我想,當user
選擇從下拉documents
下,分配這些選定的文件到許多選擇板。所以這是許多文件與許多板塊。我已經嘗試過並檢查了文檔http://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models
均爲sync
和attach
方法。
上面的代碼生成錯誤
調用未定義的方法照亮\數據庫\雄辯\收藏::文檔()
任何想法我做錯了嗎?我是否以正確的方式做這件事?
我不明白這一點。您能否請編輯我的代碼並將其展示給我。我需要先找到我認爲的身份證..對吧? – user3641381
@ user3641381檢查編輯 –
我測試了您的更新代碼。它的工作原理,只在第二個'foreeach'你得到一個完整性約束衝突 - 1062重複輸入'1-1'' – user3641381