2016-08-30 50 views
0

對不起,我是一個相對Laravel初學者。多對多口才 - 相同型號

我有一個名爲PACS的模型。每臺PACS可以與許多其他PACS相關。從一個到另一個的關係也有一個方向,推或拉。

我PACS模式有一個多對多的關係定義爲

public function pacsRelation() { 
     return $this->belongsToMany('App\PACS', 'pacs_has_pacs', 'pacsId', 'hasPacsId')->withTimestamps()->withPivot('transferRelation'); 
    } 

我的透視表

Schema::create('pacs_has_pacs', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->timestamps(); 
      $table->integer('pacsId')->unsigned(); 
      $table->integer('hasPacsId')->unsigned(); 
      $table->enum('transferRelation', ['push', 'pull']); 

      $table->foreign('pacsId')->references('pacsId')->on('pacs'); 
      $table->foreign('hasPacsId')->references('pacsId')->on('pacs'); 
     }); 

我PACS模型表

Schema::create('pacs', function (Blueprint $table) { 
      $table->increments('pacsId'); 
      $table->timestamps(); 
      $table->string('email'); 
      $table->string('name'); 
      $table->string('fax')->nullable(); 
      $table->string('edi')->nullable(); 
      $table->string('contact'); 
     }); 

我有麻煩的我正在執行以下代碼,並且沒有行出現在我的數據透視表中並且沒有錯誤。

public function handle() 
    { 

     $this->error("The relationship is defined push or pull by how the receiving party is able to retreive images from the sending party."); 

     $valid = false; 

     while (!$valid) { 

      $receiving = $this->ask('Receiving PACS name'); 

      try { 
       $pacs = PACS::where('name', '=', $receiving)->firstOrFail(); 
      } catch (ModelNotFoundException $e) { 
       $this->error('This PACS does not exist'); 
       continue; 
      } 

      $valid = true; 

     } 

     $this->info($pacs); 

     $valid = false; 

     while (!$valid) { 

      $sending = $this->ask('Sending PACS name'); 

      try { 
       $sendingPacs = PACS::where('name', '=', $sending)->firstOrFail(); 
      } catch (ModelNotFoundException $e) { 
       $this->error('This PACS does not exist'); 
       continue; 
      } 

      $valid = true; 

     } 

     $this->info($sendingPacs); 

     $relation = $this->choice('Push or Pull relation?', ['push', 'pull']); 

     $pacs->pacsRelation()->save($sendingPacs, ['transferRelation'=>$relation]); 

     $this->info('Relationship successfully defined.'); 

    } 

有什麼明顯的我失蹤或我走了這個錯誤的方式嗎?

+0

看看'attach()'... https://laravel.com/docs/5.3/eloquent-relationships#updating-many-to-many-relationships – Sherif

回答

0

經過許多小時的研究後,解決了這個問題的問題歸咎於Laravel無法識別我的表的主鍵。

我不得不定義

protected $primaryKey = 'pacsId'; 
我的PACS模型

和我離開。