0

Создал БД

posts

id - integer
title - string
body - text

videos

id - integer
title - string
url - string

comments

id - integer
body - text
commentable_id - integer
commentable_type - string

Для каждой Модели определил отношения

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

В контроллере написано

  public function index()
    {
        $comment = App\Comment::find(1);

        $commentable = $comment->commentable;
        dd( $commentable);
    }

Но мне выдает ошибку

FatalErrorException in Model.php line 827: Class 'post' not found

В базе пробовал менять название commentable_type на Post все равно ошибка.введите сюда описание изображения

Что мне сделать чтобы отношения работали?

1 ответ 1

1

Ниже того примера в документации, который вы пытаетесь воспроизвести, написано, что Laravel хранит полное название класса (с пространством имён: App\Post)

Чтобы указать свои, сделайте так:

Relation::morphMap([
    'post' => 'App\Post',
    'video' => 'App\Video',
 // 'как-храним' => 'класс',
]);

Сделать это можно в App\Providers\AppServiceProvider::boot(), например.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.