2015-11-24 92 views
0

我有這樣的設置。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

均爲syncattach方法。

上面的代碼生成錯誤

調用未定義的方法照亮\數據庫\雄辯\收藏::文檔()

任何想法我做錯了嗎?我是否以正確的方式做這件事?

回答

0

您試圖從整個模型集合中檢索一個模型的關係,這將不起作用。我假設你發現許多方法正在返回基於你傳入的ID數組的模型集合。

如果你想多板連接到一個文檔,使用:

$document->plates()->attach($plate_ids); 

如果你想許多文件附加到板:

$plates->documents()->attach($document_ids); 

編輯:

可能有一個更優雅的方式來做這件事,而不會更改你的代碼太多,但你可以做一些事情,如foll因爲:

$plate_filter = [ 
    'plate_id_1' => 1, 
    'plate_id_2' => 2, 
    'plate_id_3' => 3, 
]; 


$doc_filter = [ 
    'recipe_id' => 1, 
    'procedure_id' => 2, 
]; 

// attach many docs to plates 
$plates = Plate::findMany($plate_filter); 
$docs = Document::findMany($doc_filter); 

// Loop over the selected plates, attach selected docs 
foreach($plates as $plate) { 

    // $doc_ids = get your document id's here, use lists or something 
    $plate->documents()->attach($doc_ids); 
} 

// Loop over the selected docs, attach selected plates 
foreach($documents as $document) { 

    // You already have your plate id's in your first array, 
    // simply use array_values to return a new array containing 
    // only the plate id's 
    $document->plates()->attach(array_values($plate_filter)); 
} 

這將會是方便的,如果你可以通過收集到的attach(),我不知道你是否能和我找不到人做這件事對谷歌的任何引用。

+0

我不明白這一點。您能否請編輯我的代碼並將其展示給我。我需要先找到我認爲的身份證..對吧? – user3641381

+0

@ user3641381檢查編輯 –

+0

我測試了您的更新代碼。它的工作原理,只在第二個'foreeach'你得到一個完整性約束衝突 - 1062重複輸入'1-1'' – user3641381