Inlogic's avatar

laravel polymorphic relation custom foreign column

Howdy here i'm trying to set a custom foreign key for my one-one polymorphic relations below is my code

i have AttendanceNotice Model

public function reportable(): MorphTo
    {
        return $this->morphTo(__FUNCTION__, 'reporter_type', 'reporter_id');
    }

Guardian Model

    public function report()
    {
        return $this->morphOne(AttendanceNotice::class, 'reportable');
    }

Employee Model

    public function report()
    {
        return $this->morphOne(AttendanceNotice::class, 'reportable');
    }

so when i retrieve attendanceNotice record its using the primary key of each related model which as i expect is the default but what i want to achieve

  1. use another column as the foreign key instead of the id of each related model
  2. add some extra query constraint when retrieving record via AttendanceNotice::query()
$res = AttendanceNotice::query()->withoutGlobalScopes()
        ->with('reportable')->get();

Thanks

0 likes
3 replies
tisuchi's avatar

@inlogic How about this?

$res = AttendanceNotice::query()
    ->withoutGlobalScopes()
    ->join('guardians', function ($join) {
        $join->on('guardians.custom_column', '=', 'attendance_notices.reportable_id')
             ->where('attendance_notices.reportable_type', Guardian::class);
    })
    ->orWhere(function ($query) {
        $query->join('employees', function ($join) {
            $join->on('employees.custom_column', '=', 'attendance_notices.reportable_id')
                 ->where('attendance_notices.reportable_type', Employee::class);
        });
    })
    ->get();
1 like

Please or to participate in this conversation.