Self JOIN query with Symfony entity -
here's table :
my category entity (without getter/setter):
/** * @var int * * @orm\column(name="id", type="integer") * @orm\id * @orm\generatedvalue(strategy="auto") */ private $id; /** * @var string * * @orm\column(name="name", type="string", length=255) */ private $name; /** * @var string * * @orm\column(name="slug", type="string", length=255, nullable=true) */ private $slug; /** * @var int * @gedmo\treeleft * @orm\column(name="lft", type="integer") */ private $lft; /** * @var int * @gedmo\treelevel * @orm\column(name="lvl", type="integer") */ private $lvl; /** * @var int * @gedmo\treeright * @orm\column(name="rgt", type="integer") */ private $rgt; /** * @gedmo\treeroot * @orm\manytoone(targetentity="category") * @orm\joincolumn(name="root", referencedcolumnname="id", ondelete="cascade") */ private $root; /** * @gedmo\treeparent * @orm\manytoone(targetentity="category", inversedby="children") * @orm\joincolumn(name="parent", referencedcolumnname="id", ondelete="cascade") */ private $parent; /** * @orm\onetomany(targetentity="category", mappedby="parent") * @orm\orderby({"lft" = "asc"}) */ private $children;
in controller, if :
$category= $this->container->get('app.category.manager')->getcategorybyslug($category_slug); $root = $term->getroot();
doctrine execute 2 queries, 1 category itself, , 1 root of category. create own repository function join 2 entities in 1 query. i've tried many things query builder, i'm completly lost.
first, create custom repository
class entity.
then, paste method following into:
class categoryrepository extends entityrepository { public function getrootbycategoryslug($slug) { return $this->getentitymanager() ->createquerybuilder() ->from('yourbundle:category', 'c') ->where('c.slug = :slug') ->setparameter('slug', $slug) ->leftjoin('c.root', 'r') // join association ->select('r') // fetch association ->getquery() ->getresult() ; } }
and use follows:
$repo = $this->getdoctrine()->getmanager()->getrepository('yourbundle:category'); $rootcategory = $repo->getrootbycategoryslug('your_slug');
Comments
Post a Comment