php - 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() 关系却不是。我不确定我在这里做错了什么..任何帮助将不胜感激。
解决方案
好的,所以我弄清楚发生了什么。这可能是 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。
推荐阅读
- java - 为什么 passwordEncoder() 是 @Bean?
- c# - WPF 选择输入音频并设置输出设备音频
- ibm-integration-bus - IIB 收集器节点和交易
- reactjs - 样式化组件不会在页面加载时应用任何样式
- css - 如何在angular.json的lazyload css中添加散列
- javascript - 如何使用 d3.js 将外部组添加到现有 svg?
- sharepoint - 如何在 Application Insights 监控 SharePoint 站点中获取唯一用户?
- r - 从 R 到 SQL 的 RODBC 连接失败
- multithreading - 为什么没有强制使用多核的软件?
- unix - 保存文件时如何添加序言?