そもそもそんなテーブル設計は間違っているということはいったんさておき、表題の対応しなければいけないことがあったのでメモとして残す
default_templates
- template_id
- name
user_created_templates
- id
- name
reports
- id
- templatable_id
- templatable_type
運用者が頻繁に更新する自動採番IDを持たないテーブルと、ユーザーが自分でCURDするテーブルがあってそれらをポリモーフィックで呼び出したいというケース。
いずれのテーブルもプライマリキーがidという場合にはモデル内部でmorphTo
で参照すればいい。
今回のケースで言えばtemplatable_type
に応じて参照するキーを動的に変更したいので下記のようにすると参照可能。
Models/report.php
class report exteds Model
{
public function templatable()
{
$ownerKey = $this->getAttribute('templatable_type') === 'App\Models\DefaultTemplate'
? 'template_id'
: 'id';
return $this->morphTo('templatable', null, null, $ownerKey);
}
}