1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel6でmorphToのリレーション先テーブルの参照するカラムを変更したい時

Posted at

そもそもそんなテーブル設計は間違っているということはいったんさておき、表題の対応しなければいけないことがあったのでメモとして残す

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);
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?