【发布时间】:2017-11-02 09:34:18
【问题描述】:
我想根据这个关系显示员工部门
这里是 JobHistory 表架构
Schema::create('JobHistories', function (Blueprint $table) {
$table->increments('id');
$table->integer('employees_id');
$table->integer('Jobs_id');
$table->integer('Departments_id');
$table->date('start_date');
$table->timestamps();
});
这是员工模型
public function jobs(){
return $this->hasMany(JobHistory::class,'employees_id','id');
}
public function getDepartment()
{
$dep = JobHistory::where('employees_id', $this->id)->orderBy('start_date', 'desc')->first();
return ($dep) ? $dep->department() : '';
}
这是 JobHistory 模型上的函数
public function department()
{
return $this->belongsTo(Department::class, 'Departments_id', 'id');
}
最后我想像这样在视图上显示它:
@foreach($employee as $row)
<tr>
<td>{{$row->name}}</td>
<td>
{{$row->getDepartment->name or '-'}}
</td>
</tr>
@endforeach
问题是,如果员工还没有任何工作经历,如何处理异常?我尝试在刀片验证中使用 is_null()、empty() 和 isset()。但没有任何效果。
【问题讨论】:
-
在这种情况下处理异常似乎有点矫枉过正,您可能只想检查部门关系的存在 - 首先加载并检查部门并做出决定 - 我明白你想要做什么,但是那行不通 :) 没有工作的“员工”似乎有点奇怪,但我可以想象一个用例......
标签: laravel orm exception-handling