Ranx99
5 months ago

Select specific fields by polymorphic type while using 'with'?

Posted 5 months ago by Ranx99
class Lesson extends Model
{
    public function content()
    {
        return $this->morphTo();
    }
}
Schema::create('lessons', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('channel_id');
    $table->string('title');
    $table->nullableMorphs('content');
    $table->timestamps();

    $table->foreign('channel_id')->references('id')->on('channels')->onDelete('cascade');
});
Schema::create('videos', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('size');
    $table->string('path');
    $table->timestamps();
});
Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('body');
    $table->string('reading_time');
    $table->timestamps();
});

A lesson can have a Video or an Article as a content, now everything works fine, But I am having a trouble in selecting specific fields while eager loading the content.

Channel::whereId($channelId)->with(['lessons'=> function ($query) {
    $query->with('content:id,size');
}])->first();

Since Lesson content can be Video or an Article an error will be shown:

Column not found: 1054 Unknown column 'size' in 'field list' (SQL: select `id`, `size` from `articles` where `articles`.`id` in (168))

How can I the fields I want while eager loading based on the polymorphic relation type?

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