首页 > 解决方案 > Laravel - 多态关系不起作用

问题描述

所以我有以下代码:

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');
    }
}

然后在 AppServiceProvider.php 我有以下内容:

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
        ]);

    }

然后我在我的 api 路由中有一个测试路由,它检查列表是否正在加载,它返回 null:(是的,我已经验证了该部分本身存在)

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

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

我的 PageSection 数据库模式是 entity_type 告诉模型是什么,而 id_Entity 是该模型的外键,在引用的表上被命名为“id”。

morphMap 中定义的其他关系工作正常,但由于某种原因,PageSection 中的 list() 关系却不是。我不确定我在这里做错了什么..任何帮助将不胜感激。

标签: phplaraveleloquent

解决方案


好的,所以我弄清楚发生了什么。这可能是 Laravel 的 morphMap 的一个错误。我使用 0 作为 PageSection::TYPE_CURATED 常量,这是一个错误的值。当我切换到:

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
]);

一切正常。似乎 Laravel 不喜欢值 0。


推荐阅读