我有我的Eloquent
Models
看起来像这样内的各种关系:Laravel雄辩 - 不运行关系查询,如果列值为NULL或0
public function main_image()
{
return $this->hasOne(Media::class, 'id', 'main_image_id');
}
然而,它会运行一个SQL查询,如果main_image_id
是空或0,所以我结束了一些查询的是这样的:
select * from `media` where `media`.`id` is null and `media`.`id` is not null limit 1
这显然不会返回任何东西,但还是浪费资源。有什么方法可以自动检查吗?
目前我所做的是有一个方法,如hasMainImage()
,检查main_image_id
是不是空的,但不是0,但很多目前的系统已经使用的关系,我想知道如果我可以添加检查关系方法本身?
我曾尝试添加一个检查到它并返回null
如果该列没有实际值,但我有Exception
它必须返回一个关系对象。或者,如果我试图贪婪加载它,我收到以下错误:
Call to a member function addEagerConstraints() on null
public function main_image()
{
if (!$this->main_image_id) {
return null;
}
return $this->hasOne('App\Modules\Media\Models\Media', 'id', 'main_image_id');
}
感谢您的帮助!
编辑: 一个或许更明显的例子:
$page = Page::find(1);
var_dump($page->main_image); // This will run a query as shown above that is guaranteed to return nothing
// Since at this point system knows that $page->main_image_id is 0 or null, I would like to use that to not run the query and automatically set $page->main_image to null
做一个'with'使用额外的资源。你首先不应该这样做,不要到处做,然后试着绕过它。 – apokryfos
'with'并不是随处可见,只有一次加载多个模型。当只加载单个实例时,不会使用'with',并调用像'$ page-> main_image'这样的调用。这些是我试图在这里优化的电话 – Giedrius
如果你这样做,没有额外的好处。连接将以任何方式发生,它只会返回更少的东西。我当然假设你在这里有一对一的关系。 – apokryfos