Laravel 树形分类目录为父目录和子目录都获取到字段

新手上路,请多包涵

我需要用树形显示分类目录,我用的 relationship

public function children()
{
    return $this->hasMany(self::class, 'parentid');
}

但是我还需要为父目录和子目录都显示图标,图标存储在另一个attachment表里

public function iconData()
{
    return $this->hasOne(Attachment::class, 'id', 'iconId');
}

控制器里eager load了图标:

public function index(ProductCategory $productCategory)
{
    return new ProductCategoryCollection(ProductCategory::with(['children', 'iconData'])->where('parentid', '=', 0)->get());
}

但是这样只能获取到父目录的,所以我把relationship改成这样:

public function children()
{
    return $this->hasMany(self::class, 'parentid')->with(['iconData']);
}

现在父目录和子目录都有图标了。但是我发现laravel会用两条SQL去分别获取父目录和子目录的:

bindings: ["865", "867"]
connection: {}
connectionName: "mysql"
sql:
"select * from attachment where attachment.id in
(?, ?)"
time: 1.61

bindings: ["864", "866"]
connection: {}
connectionName: "mysql"
sql: "select * from
attachment where attachment.id in (?, ?)"
time:
0.6

有没有什么更好的办法达到这个效果?

阅读 997
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题