<?php

namespace Hilco\Models;

use DB;

trait SelectsRelatedCount {
    public function scopeSelectRelatedCount($query, $relationName, $fieldName = null) {
        $relation = $this->$relationName();
        $related = $relation->getRelated();
        $fieldName = $fieldName ?: $relationName;

        $subQuery = $relation->getRelationCountQuery($related->newQuery(), $query);

        $select = '(' . $subQuery->toSql() . ') as ' . $fieldName;

        return $query->addSelect(DB::raw($select));
    }
}