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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…