无法引用 Laravel 中主键以外的外键

  • 本文关键字:引用 Laravel laravel eloquent
  • 更新时间 :
  • 英文 :


我有两个模型:部门和部门类型。在部门类型中,我有一个列"深度"作为部门的外键(字段:hirarchy_lvl(。也就是说,我正在尝试让 DepartmentType 标签显示在视图中,但一直失败......

这是我所拥有的:

部门.php:

public function departmentType()
{
return $this->belongsTo(DepartmentType::class, 'depth', 'hirarchy_lvl');
}

部门类型.php

public function department()
{
return $this->hasMany(Department::class, 'hirarchy_lvl', 'depth');
}

数据库架构创建:

public function up()
{
Schema::create('department_types', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->bigInteger('depth')->unsigned()->unique();
$table->string('hirarchy_lvl_name');
});
DB::table('department_types')->insert(array('created_at' => now(), 'depth' => '10', 'hirarchy_lvl_name' => 'company'));
DB::table('department_types')->insert(array('created_at' => now(), 'depth' => '20', 'hirarchy_lvl_name' => 'department'));
DB::table('department_types')->insert(array('created_at' => now(), 'depth' => '30', 'hirarchy_lvl_name' => 'team'));
DB::table('department_types')->insert(array('created_at' => now(), 'depth' => '40', 'hirarchy_lvl_name' => 'individual'));

Schema::table('departments', function (Blueprint $table) {
$table->foreign('hirarchy_lvl')->references('depth')->on('department_types')->onDelete('NO ACTION')->change();    //shall reference other objective
});
}

在控制器中:

public function listDepartmentsByHirarchy($hirLvl = 0){
if($hirLvl){
$departments = Department::where('hirarchy_lvl', $hirLvl)->get();           
}
else 
{
$departments = Department::get();                       
}
$department_types = DepartmentType::get();
return view('configcenter/listDepartments', compact('departments', 'department_types'));
}

在视图中进行测试:

<td>
{{$department}}
</td>

给我:

{"id":2,"created_at":"2019-12-18 13:04:11","updated_at":null,"description":"dep1","parent_dep":{"id":1,"created_at":"2019-12-18 13:04:11","updated_at":null,"description":"company","parent_dep":1,"hirarchy_lvl":10},"hirarchy_lvl":20}

让我得出结论,外键没有得到正确解析(因为它只是值而不是我在这里需要的对象(。

现在,在研究了文档(https://laravel.com/docs/5.4/eloquent-relationships#has-many-through(和几篇帖子之后,我忍不住问了一个菜鸟问题:如何正确引用外键,以便我可以处理视图中的对象?

感谢任何提示...

我相信你的Department::departmentType()关系是不正确的。应切换字段。

定义关系的belongsTo侧时,第二个参数是定义模型上的字段(departments.hirarchy_lvl(,第三个参数是相关模型上的字段(department_types.depth(。

在定义关系的hasOne/hasMany面时,情况正好相反。第二个参数是相关模型上的字段,第三个参数是定义模型上的字段。

部门.php:

public function departmentType()
{
return $this->belongsTo(DepartmentType::class, 'hirarchy_lvl', 'depth');
}

部门类型.php

public function department()
{
return $this->hasMany(Department::class, 'hirarchy_lvl', 'depth');
}

最新更新