我需要用树形显示分类目录,我用的 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 * fromattachment
whereattachment
.id
in
(?, ?)"
time: 1.61bindings: ["864", "866"]
connection: {}
connectionName: "mysql"
sql: "select * fromattachment
whereattachment
.id
in (?, ?)"
time:
0.6
有没有什么更好的办法达到这个效果?