2016-11-23 153 views
2

我是新來的Laravel。 這裏是我的架構:雄辯Laravel加入模型5.3

Schema::create('cluster_info', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('code')->unique(); 
      $table->string('pa_lastname'); 
      $table->string('pa_firstname'); 
      $table->string('pa_middlename'); 
      $table->string('pa_suffix'); 
      $table->integer('branch_id'); 
      $table->timestamps(); 

     }); 
Schema::create('cluster_grouping', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('cluster_id'); 
      $table->integer('client_id'); 
      $table->timestamps(); 

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

     }); 

我想加入cluster_infobranch。所以在我的Cluster_Info型號:

public function Branches(){ 
     return $this->hasOne('App\Branch'); 
    } 

,當我把它在我的控制有null

$cluster = new App\Cluster_Info; 
dd($cluster->Branches()); 
+2

什麼是在''branch'你cluster_info'外鍵? – Tiger

+1

在cluster_info表的分支表中定義外鍵。 –

+0

@BalrajAllam如何在clusteri_info中定義分支表的外鍵? –

回答

0

請仔細閱讀here,什麼是外鍵以及如何寫在表的外鍵。見laravel here

如果添加的表名和外鍵適當的比你的關係應該工作的命名規則的討論。否則你可以使用下面的方法,並把你的外鍵作爲第二個參數。閱讀Deatils爲One to One Relationship

return $this->hasOne('App\Branch', 'foreign_key'); 
0

檢查本地和外鍵:

return $this->hasOne('App\Branch', 'id', 'cluster_id'); 

這可能是你在你的控制器寫的方式,因爲爲了生存的關係,這種關係的方法應被要求在現有Cluster_Info例如,像這樣:

$clusters = Cluster_Info::all(); 
foreach($clusters as $clusterInfo) { 
    dump($clusterInfo->Branches()); 
} 

或者使用eager loading

$clusters = Cluster_Info::with('Branches')->get(); 

同時確保雄辯知道你的表名,因爲我不確定你在這裏遇到Laravel的約定。

class Cluster_Info { 
    protected $table = 'cluster_info'; 
} 

爲了增強可讀性,我會建議使用的方法類似branch()而不是Branches(),它應該只返回只有一個結果。還可以看看Eloquent model conventions,它們可以讓你的生活變得如此簡單。

+0

我試過急於加載,這是結果 未找到列:1054'where子句'中的未知列'branch.cluster__information_id'(SQL:select * from'branch' where'branch'.'cluster__information_id' in(1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26, 27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51, 52,53,54,64,67)) –

+0

查看更新答案的第一行。 –