i have three tables that has poly morphic relationship, maintenance: -id -stock_SNW_issue_id
Obsolescence: -id -stock_SNW_issue_id
Staff_performance -id -performance_id -performance_type
I want to get id from maintenance table where stock_SNW_issue_id = $issueId, and check whether that id exists on the staff_performance table or not.
This is my function inside controller:
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]);
}
this is my staff_performance model:
public function performance()
{
return $this->morphTo();
}
this is maintenance model:
public function staffPerformances()
{
return $this->morphMany(Staff_Performances::class, 'performance');
}
this is obsolescence model:
public function staffPerformances()
{
return $this->morphMany(Staff_Performances::class, 'performance');
}
I got two issues: 1- This code runs infinitively 2- gives performance_id column not found error.
The infinite loop issue in your code seems to be due to the way you're using morph relationships and eager loading. Also, the "column not found" error is likely because the
Staff_Performancesmodel doesn't have a column namedperformance_id. Instead, it's using polymorphic relations. Here's how you can refactor your code to address both issues:First, ensure that your
Staff_Performancesmigration has the necessary columns for polymorphic relations, typicallyperformance_id,performance_type, and other relevant columns.Assuming your
Staff_Performancesmodel is correctly set up with morphTo relations, here's how you can refactor yourisIssueAssignedfunction:Ensure that you have imported the necessary models at the top of your controller.
This refactored code directly queries the
Staff_Performancestable for the existence of a record where theperformance_idmatches the maintenance record ID and theperformance_typematches the type of the maintenance record. This should avoid the infinite loop issue and resolve the "column not found" error.Remember to adjust the namespaces and class names as per your actual application structure.