Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

php - Laravel 8.0 How to eager load when using MorphTo - MorphMany relationship

I'm creating a blog with articles, tags, comments and likes. Every article can have tags, comments and likes. When displaying all articles, I want to eager load its user, tags, comments and likes. The problem is, that likes are in morph relationship with articles and they don't load with articles.

Article.php

public function likes(): MorphMany
{
    return $this->morphMany(Like::class, 'likeable');
}

Like.php

public function likeable(): MorphTo
{
    return $this->morphTo();
}

2021_01_26_090103_create_likes_table.php

public function up()
{
    Schema::create('likes', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id');
        $table->morphs('likeable');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

ArticleController.php

public function index()
{
    $articles = Article::with(['user', 'tags', 'comments', 'likes'])->latest()->paginate(10);

    return view('articles.all-articles', compact('articles'));
}

But telescope reports these DB queries:

How can I make it to reduce the DB queries? Thanks

question from:https://stackoverflow.com/questions/65918645/laravel-8-0-how-to-eager-load-when-using-morphto-morphmany-relationship

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have a look at this link Eager Load Morph


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...