Laravel,当数据库为空时,我会收到错误消息,否则不会,但我必须使用它
Laravel, When database is empty I'm getting error otherwise not but I have to use this
$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 还是类似的东西
真的,你应该正确配置你的关系,这样你就可以做到
$companies = Company::all();
foreach($companies as $company){
foreach($company->employees as $employee){
if($employee->active){
....
}
}
}
但在您的情况下,您可以将第一行更改为
$employee = Employee::where('user_id', Auth::user()->id)->first();
这将 return 一个 Employee
对象集合而不是数组,因此您不需要使用 [index]
来获取第一个对象。
@Joe 解决方案是正确的。您可以预先加载公司和员工以避免 N+1 查询问题。这个案例有一个官方的例子:
https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
$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 还是类似的东西
真的,你应该正确配置你的关系,这样你就可以做到
$companies = Company::all();
foreach($companies as $company){
foreach($company->employees as $employee){
if($employee->active){
....
}
}
}
但在您的情况下,您可以将第一行更改为
$employee = Employee::where('user_id', Auth::user()->id)->first();
这将 return 一个 Employee
对象集合而不是数组,因此您不需要使用 [index]
来获取第一个对象。
@Joe 解决方案是正确的。您可以预先加载公司和员工以避免 N+1 查询问题。这个案例有一个官方的例子: https://laravel.com/docs/5.7/eloquent-relationships#eager-loading