我有三个具有多态关系的表, 维护: -ID -stock_SNW_issue_id
过时: -ID -stock_SNW_issue_id
员工表现 -ID -性能_id -性能类型
我想从维护表中获取id,其中stock_SNW_issue_id = $issueId,并检查该id是否存在于staff_performance表中。
这是我在控制器内的功能:
public function isIssueAssigned($issueId)
{
$bio_id = bio_md_maintenance_dealer::where('stock_SNW_issue_id', $issueId)->value('id');
$isAssigned = Staff_Performances::whereHas('performance', function ($subQuery) use ($bio_id) {
$subQuery->where('performance_id', $bio_id)
->where('performance_type', 'App\Models\Hospitals\MaintenanceReport\bio_md_maintenance_dealer');
})->exists();
return response()->json(['isAssigned' => $isAssigned]);
}
这是我的员工绩效模型:
public function performance()
{
return $this->morphTo();
}
这是维护模型:
public function staffPerformances()
{
return $this->morphMany(Staff_Performances::class, 'performance');
}
这是过时的模型:
public function staffPerformances()
{
return $this->morphMany(Staff_Performances::class, 'performance');
}
我有两个问题: 1-此代码无限运行 2-给出 Performance_id 列未找到错误。
代码中的无限循环问题似乎是由于您使用变形关系和急切加载的方式造成的。此外,“未找到列”错误可能是因为
Staff_Performances
模型没有名为 performance_id
的列。相反,它使用多态关系。以下是重构代码以解决这两个问题的方法:
首先,确保您的
Staff_Performances
迁移具有多态关系所需的列,通常是 performance_id
、performance_type
和其他相关列。
假设您的
Staff_Performances
模型已使用 morphTo 关系正确设置,以下是重构您的 isIssueAssigned
函数的方法:
use App\Models\Staff_Performances;
use App\Models\Hospitals\MaintenanceReport\bio_md_maintenance_dealer;
public function isIssueAssigned($issueId)
{
// Get the maintenance record ID based on the issue ID
$maintenanceId = bio_md_maintenance_dealer::where('stock_SNW_issue_id', $issueId)->value('id');
// Check if the maintenance record is assigned in staff performance
$isAssigned = Staff_Performances::where('performance_id', $maintenanceId)
->where('performance_type', 'App\Models\Hospitals\MaintenanceReport\bio_md_maintenance_dealer')
->exists();
return response()->json(['isAssigned' => $isAssigned]);
}
确保您已在控制器顶部导入了必要的模型。
此重构代码直接查询
Staff_Performances
表中是否存在performance_id
与维护记录ID匹配、performance_type
与维护记录类型匹配的记录。这应该可以避免无限循环问题并解决“未找到列”错误。
请记住根据您的实际应用程序结构调整命名空间和类名称。