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;
}