doutidi5037
2019-03-21 20:12
浏览 66
已采纳

Laravel - 多态关系不起作用

So I have the following code:

class PageSection extends Model {
    protected $table = "PageSection";

    const TYPE_CURATED = 0;
    const TYPE_AUTOMATED = 1;

    public function list() {
        return $this->morphTo('list', 'entity_type', 'id_Entity');
    }
}

then in AppServiceProvider.php I have the following:

use App\PageSection;
use App\PageSectionGroup;
use App\PageListEntry;
use App\RSSFeed;
use App\Shortcut;
use App\RSSEpisode;
use App\PageList;
use App\AutomatedList;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Relation::morphMap([
            'Section'                    => PageSection::class,  
            'SectionGroup'               => PageSectionGroup::class,
            PageSection::TYPE_CURATED    => PageList::class,
            PageSection::TYPE_AUTOMATED  => AutomatedList::class,
            PageListEntry::TYPE_FEED     => RSSFeed::class,
            PageListEntry::TYPE_SHORTCUT => Shortcut::class,
            PageListEntry::TYPE_EPISODE  => RSSEpisode::class
        ]);

    }

Then I have a test route in my api routes that checks to see if the list is being loaded, and it returns null: (Yes, I've verified that the section itself exists)

Route::get('/test', function() {
    $section = PageSection::with(['list', 'type'])->find(1);

    // this returns null
    return $section->list;
});

My database schema for PageSection is such that entity_type tells what the model is, and id_Entity is the foreign key for that model, which is named 'id' on the referenced table.

The other relations defined in morphMap are working properly, yet for some reason the list() relationship in PageSection is not. I'm not sure what I'm doing wrong here.. any help would be appreciated.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjianshen4871 2019-03-21 21:11
    已采纳

    Ok, so I figured out what was going on. It's probably a bug with Laravel's morphMap. I was using 0 for the PageSection::TYPE_CURATED constant, which is a falsey value. When I switched to:

    Relation::morphMap([
        'PageList'                   => PageList::class,
        'AutomatedList'              => AutomatedList::class,
        'Section'                    => PageSection::class,  
        'SectionGroup'               => PageSectionGroup::class,
        PageListEntry::TYPE_FEED     => RSSFeed::class,
        PageListEntry::TYPE_SHORTCUT => Shortcut::class,
        PageListEntry::TYPE_EPISODE  => RSSEpisode::class
    ]);
    

    it all worked fine. Seems like Laravel doesn't like the value 0.

    点赞 打赏 评论

相关推荐 更多相似问题