Php 在雄辩的Laravel 5.3中加入模型
我是拉雷维尔的新手。 这是我的模式:Php 在雄辩的Laravel 5.3中加入模型,php,laravel,laravel-5,model,eloquent,Php,Laravel,Laravel 5,Model,Eloquent,我是拉雷维尔的新手。 这是我的模式: Schema::create('cluster_info', function (Blueprint $table) { $table->increments('id'); $table->string('code')->unique(); $table->string('pa_lastname'); $table->string('
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\u info
到分支
。因此,在我的Cluster\u Info
模型中:
public function Branches(){
return $this->hasOne('App\Branch');
}
当我在控件中调用它时,它有null
值
$cluster = new App\Cluster_Info;
dd($cluster->Branches());
请阅读什么是外键以及如何在表中写入外键。请参阅laravel的命名约定讨论
若您正确地添加了表名和外键,那个么您的关系应该可以正常工作。否则,您可以使用下面的方法并将外键作为第二个参数传递。读死亡之书
检查您的本地和外键:
return $this->hasOne('App\Branch', 'id', 'cluster_id');
这可能是您在控制器中编写的方式,因为为了存在关系,应该在现有的Cluster\u Info
实例上请求relationship方法,如下所示:
$clusters = Cluster_Info::all();
foreach($clusters as $clusterInfo) {
dump($clusterInfo->Branches());
}
或使用:
还要确保Elount知道您的表名,因为我不确定您是否符合Laravel的约定
class Cluster_Info {
protected $table = 'cluster_info';
}
为了可读性,我建议使用类似
branch()
的方法,而不是branchs()
,因为它应该只返回一个结果。再看一下,,它们可以让你的生活变得更轻松。在分支中,你在集群信息中的外键是什么?在集群信息表的分支表中定义外键。@BalrajAllam我如何在集群信息中定义分支表的外键?使用php artisan migrate:Rollback
回滚迁移,然后添加$table->integer('cluster\u info\u id')
$table->foreign('cluster\u info\u id')->引用('id')->在分支架构中的('cluster\u info')
上。我尝试了快速加载,但未找到结果列:“where子句”中的1054未知列“branch.cluster\u information\u id”(SQL:select*frombranch
wherebranch
cluster\uu information\u 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,26,28,29,30,32,33,34,35,37,39,40,41,42,43,44,45,46,48,49,50,51,54,67))
$clusters = Cluster_Info::with('Branches')->get();
class Cluster_Info {
protected $table = 'cluster_info';
}