What is the problem of changing the type field string to int of laravel Custom Polymorphism Association?

Custom polymorphic associated type fields
write mapping

[
1=>"App\Post",
2=>"App\Commit",
]

but I have multiple tables with many-to-many relationships?

requires another set of mappings

[
1=>"App\Other",
2=>"App\User",
]

the table types of polymorphic associations all use int , but 1 maps different tables in different model . What should I do?

  public function click()
    {
        if ($this->type == 1) {
            return $this->belongsTo("App\Models\HomeList", "click_id");
        }
        if ($this->type == 2) {
            return $this->belongsTo("App\Models\SlideShow", "click_id");
        }
        if ($this->type == 3) {
            return $this->belongsTo("App\Models\ReleaseTask", "click_id");
        }

        return $this->belongsTo("App\Models\HomeList", "click_id");
    }

the result of the above code $this- > type this value cannot be parsed, and a if is not entered!
what should I do?

Mar.21,2021

how do you call this click method? is it worthless to print $this- > type?


encountered the same problem. I don't know how the subject solved it at that time. I solved it on my side, and the principle is to use the acquirer .

clipboard.png

clipboard.png

clipboard.png

paste the code below.

  make better use of the polymorphic association of Laravel-some tricks in development-SegmentFault think  

Menu