Created
July 6, 2015 11:23
-
-
Save bastiankoetsier/440699f03aefd5eb8975 to your computer and use it in GitHub Desktop.
Forces eloquent to join tables instead of eager-loading. useful for filtering & orderin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment