fredyounan
9/25/2016 - 2:26 PM

Forces eloquent to join tables instead of eager-loading. useful for filtering & orderin

Forces eloquent to join tables instead of eager-loading. useful for filtering & orderin

    /**
     * @param $query
     * @param $relation_name
     * @param string $operator
     * @param string $type
     * @param bool $where
     * @return mixed
     */
    public function scopeModelJoin($query, $relation_name, $operator = '=', $type = 'left', $where = false)
    {
        /** @var \Illuminate\Database\Eloquent\Relations\Relation $relation */
        $relation = $this->$relation_name();
        $table = $relation->getRelated()->getTable();
        $one = $relation->getQualifiedParentKeyName();
        $two = $relation->getForeignKey();

        if (empty($query->columns)) {
            $query->select($this->getTable().".*");
        }
        foreach (\Schema::getColumnListing($table) as $related_column) {
            $query->addSelect(new Expression("`$table`.`$related_column` AS `$table.$related_column`"));
        }
        return $query->join($table, $one, $operator, $two, $type, $where); //->with($relation_name);
    }