为什么我的Laravel Morphmap返回空

时间:2017-07-04 21:37:41

标签: laravel

我有一张这样的表:

    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('comment_id');
        $table->string('comment_type');
        $table->text('comment');
        $table->timestamps();
    });

这样填充:

INSERT INTO `job`.`comments` (`id`, `user_id`, `comment_id`, `comment_type`, `comment`, `created_at`, `updated_at`) VALUES ('1', '1', '8', 'courses', 'Hello', NULL, NULL);

我有一个类似的课程模型:

<?php

namespace App\Modules\Courses\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Laravelista\Comments\Comments\Traits\Comments;

class Courses extends Model
{
    use Comments;

    protected $table = 'courses';

    public function comments()
    {
        return $this->morphMany('App\Modules\Comments\Models\Comments', 'comment');
    }

使用我的变形贴图变形我的评论模型:

<?php

namespace App\Modules\Comments\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::morphMap([
    'courses' => App\Modules\Courses\Models\Courses,
]);

class Comments extends Model
{
    public function commentable()
    {
      return $this->morphTo();
    }
}

如果我在我的行中引用我的地图并使用该类型的课程,那么它就会从Tinker中看到为空:

enter image description here

但是,如果我在数据库中的comment_type中使用完整的命名空间,那么它可以工作:

INSERT INTO `job`.`comments` (`id`, `user_id`, `comment_id`, `comment_type`, `comment`, `created_at`, `updated_at`) VALUES ('1', '1', '8', 'App\\Modules\\Courses\\Models\\Courses', 'Hello', NULL, NULL);

enter image description here

我做错了什么,我该如何解决这个问题?

编辑:我也尝试了将它放在我的应用服务提供商中的建议,但这两者都不起作用:

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试在服务提供者

中注册Relation :: morphMap()

<强> AppServiceProvider

use Illuminate\Database\Eloquent\Relations\Relation;
...
public function boot()
{
    Relation::morphMap([
         'courses' => 'App\Modules\Courses\Models\Courses',
    ]);
}

https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations

相关问题