Skip to content

Instantly share code, notes, and snippets.

@bastiankoetsier
Created July 6, 2015 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bastiankoetsier/440699f03aefd5eb8975 to your computer and use it in GitHub Desktop.
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
/**
* @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