BadMethodCallException 调用未定义的方法 App\Models\User::role()
BadMethodCallException Call to undefined method App\Models\User::role()
我编写了一个考勤员工系统来加载时间雇主的报告
我遇到了以下错误
我应该怎么做才能解决这个问题?
BadMethodCallException
调用未定义的方法 App\Models\User::role()
您是说 App\Models\User::only() 吗?
我的user.php模特:
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $appends = [
'profile_photo_url',
];
}
报表控制器
$employees = User::whereHas('role', function ($query) {
$query->where('employee');
})
->get();
$dateRange = $reportService->generateDateRange();
$timeEntries = $reportService->generateReport($request->input('employee'));
if ($timeEntries) {
$chart = new LaravelChart([
'chart_title' => 'Hours of work per day',
'chart_type' => 'line',
'report_type' => 'group_by_date',
'model' => 'App\TimeEntry',
'group_by_field' => 'time_start',
'group_by_period' => 'day',
'aggregate_function' => 'sum',
'aggregate_field' => 'total_time_chart',
'column_class' => 'col-md-8',
'continuous_time' => true,
]);
} else {
$chart = NULL;
}
您必须在 User
模型中定义关系函数 role
。像这样:
public function role() {
return $this-><Type of relation>(Role::class);
}
根据讨论,没有角色 table 因此您无法使用 User::whereHas('role')
检查
取而代之的是,您应该使用以下行
$employees = User::whereRole('employee')->get();
此外,我注意到您没有在 fillable 中添加角色,您应该将角色添加到 protected $fillable
以便考虑该列执行创建和保存等操作。
我编写了一个考勤员工系统来加载时间雇主的报告
我遇到了以下错误
我应该怎么做才能解决这个问题?
BadMethodCallException
调用未定义的方法 App\Models\User::role()
您是说 App\Models\User::only() 吗?
我的user.php模特:
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $appends = [
'profile_photo_url',
];
}
报表控制器
$employees = User::whereHas('role', function ($query) {
$query->where('employee');
})
->get();
$dateRange = $reportService->generateDateRange();
$timeEntries = $reportService->generateReport($request->input('employee'));
if ($timeEntries) {
$chart = new LaravelChart([
'chart_title' => 'Hours of work per day',
'chart_type' => 'line',
'report_type' => 'group_by_date',
'model' => 'App\TimeEntry',
'group_by_field' => 'time_start',
'group_by_period' => 'day',
'aggregate_function' => 'sum',
'aggregate_field' => 'total_time_chart',
'column_class' => 'col-md-8',
'continuous_time' => true,
]);
} else {
$chart = NULL;
}
您必须在 User
模型中定义关系函数 role
。像这样:
public function role() {
return $this-><Type of relation>(Role::class);
}
根据讨论,没有角色 table 因此您无法使用 User::whereHas('role')
检查
取而代之的是,您应该使用以下行
$employees = User::whereRole('employee')->get();
此外,我注意到您没有在 fillable 中添加角色,您应该将角色添加到 protected $fillable
以便考虑该列执行创建和保存等操作。