spoon

Polymorphic relation, SQL query fetches full model name instead of its name

Posted 3 years ago by spoon

Hi,

I'm trying to implement this : https://laracasts.com/lessons/polymorphic-huh

My Models are in the Model table, so I use namespace.

comments table

id
commentable_id
commentable_type
comment
created_at

Comment Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    public function commentable()
    {
        return $this->morphTo();
    }
}

Thing Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;


class Thing extends Model
{
    public function comments() {
        return $this->morphMany('\App\Models\Comment', 'commentable');
    }
}

If I use like this, it seeks for App\Models\Thing rather than Thing in the commentable_type column.

select * from `comments` where `comments`.`commentable_id` = '1' and `comments`.`commentable_id` is not null and `comments`.`commentable_type` = 'App\Models\Thing'

Controller

$comments = Thing::FindorFail($id)->comments;

View

@foreach($comments as $comment)
    {{$comment->comment}}
@endforeach

How can I solve this?

Please sign in or create an account to participate in this conversation.