$employee = Employee::where('user_id', Auth::user()->id)->get();
foreach (Company::all() as $company)
{
if ($company->id == $employee[0]->company_id && $company->employee_active === 1)
{
$event->menu->add([
'text' => 'Contracten',
'url' => 'dashboard/contracts',
'icon' => 'file-text',
'submenu' => [
[
'text' => 'Contract opzetten',
'url' => 'dashboard/contracts/create',
'icon_color' => 'red',
]
]
]);
}
}
使用此代码时,如果数据库为空,则会得到未定义的偏移量:0。如何得到这个写?我应该使用if还是类似的东西
答案 0 :(得分:0)
@Joe解决方案是正确的。您可以急切地加载公司和员工,以避免N + 1查询问题。有这种情况的官方示例: https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
答案 1 :(得分:-2)
真的,您应该正确配置关系,以便可以
$companies = Company::all();
foreach($companies as $company){
foreach($company->employees as $employee){
if($employee->active){
....
}
}
}
但是根据您的情况,您可以将第一行更改为
$employee = Employee::where('user_id', Auth::user()->id)->first();
这将返回Employee
对象集合而不是数组,因此您不需要使用[index]
来获取第一个对象。