2016-11-23 106 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

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