W
W
WebDev2016-07-26 15:15:18
Laravel
WebDev, 2016-07-26 15:15:18

Laravel. left join inside with?

There is a tree of tags, parent tags, child. Many-to-many relationship.
I make a selection:

Tag::with(['tags' => function($query) {
            $query->orderBy('name');
        }])
        ->leftJoin('entity_tag', 'entity_tag.tag_id', '=', 'tags.id')
        ->select(\DB::raw('COUNT(entity_tag.id) as entity_count'), 'tags.*')
        ->get();

I need the number of entities to be calculated for child tags too. Is there any way to add it to the with condition?
Something like this is needed to make it happen:
Tag::with(['tags' => function($query) {
            $query->orderBy('name');
            ->leftJoin('entity_tag', 'entity_tag.tag_id', '=', 'tags.id')
            ->select(\DB::raw('COUNT(entity_tag.id) as entity_count'), 'tags.*')
        }])
        ->leftJoin('entity_tag', 'entity_tag.tag_id', '=', 'tags.id')
        ->select(\DB::raw('COUNT(entity_tag.id) as entity_count'), 'tags.*')
        ->get();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question