i need to display category as tree view, i did it using relationship:
public function children()
{
return $this->hasMany(self::class, 'parentid');
}
but i also need to displayicon for both parent and children:
public function iconData()
{
return $this->hasOne(Attachment::class, 'id', 'iconId');
}
i eager load the relationship in controller:
public function index(ProductCategory $productCategory)
{
return new ProductCategoryCollection(ProductCategory::with(['children', 'iconData'])->where('parentid', '=', 0)->get());
}
but i only get icon data for parent, so i changed the children relationship to
public function children()
{
return $this->hasMany(self::class, 'parentid')->with(['iconData']);
}
now both parent and children have icon data. but i find that laravel fetch the attachment data with two queries, one for parent and the other for children:
bindings: [“865”, “867”]
connection: {}
connectionName: “mysql”
sql:
“select * fromattachment
whereattachment
.id
in
(?, ?)”
time: 1.61
bindings: [“864”, “866”]
connection: {}
connectionName: “mysql”
sql: “select * from
attachment
whereattachment
.id
in (?, ?)”
time:
0.6
is there more elegant way to do this?