Laravel MorphMany:访问 MorphTo 关系属性时避免 N+1 查询?

问题描述 投票:0回答:1

PHP:8.2
Laravel 框架: 11
MySQL

我们的网站上大致有以下代码来代表总体问题。

Post.php

class Post extends BaseModel
{
    public function blocks(): MorphMany
    {
        return $this->morphMany(Block::class, 'blockable');
    }
}

区块.php

class Block extends Model
{
    public function blockable(): MorphTo
    {
        return $this->morphTo();
    }

    public function alt(): string
    {
        $alt = '';

        if ($this->caption) {
            $alt = $this->caption;
        } else if ($this->blockable->title) {
            $alt = 'Block from ' . $this->blockable->title;
        }

        return $alt;
    }
}

PostController.php

$posts = Post::where('status_id', 1)
    ->with('blocks')
    ->get();

此代码工作正常并返回预期结果。但是,通过在 alt 函数中调用 $this->blockable,它会生成额外的(重复的)MySQL 查询来查找父级,即使它已经被查询并存在。有没有办法让Laravel知道blockable已经作为父级被查询了?

我们发现的一个快速解决方案如下,但我们认为有一种更雄辩的方法来实现这一目标。

public function alt(Post $blockable): string
{
    $alt = '';

    if ($this->caption) {
        $alt = $this->caption;
    } else if ($blockable->title) {
        $alt = 'Block from ' . $blockable->title;
    }

    return $alt;
}
php mysql laravel laravel-11
1个回答
0
投票

您应该像块关系一样立即加载可阻止关系。

$posts = Post::where('status_id', 1)
    ->with(['blocks', 'blocks.blockable'])
    ->get();

因为您在这里使用的是 blockable : enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.