Skip to content

Commit

Permalink
fix méthode Builder::alias() suite à une modification du comportement…
Browse files Browse the repository at this point in the history
… de la méthode Model::newInstance() dans Laravel
  • Loading branch information
lgtaxn committed Mar 20, 2019
1 parent e17bd92 commit b68e12b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 17 deletions.
21 changes: 5 additions & 16 deletions src/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,26 +45,19 @@ public function getModels($columns = ['*'])
}

/**
* Modifie l'alias de la table utilisée dans la clause "from".
* Remplace le nom de table par un alias.
* Une nouvelle instance du Builder est retournée.
*
* @param string $alias
* @return Builder
*/
public function alias($alias)
{
$table = $this->model->getTable();
$this->model->setTable($alias);

$query = $this->model->newQuery();
$query->from("$table as $alias");

return $query;
$model = $this->model->newInstance([], false, $alias);

return $model->from($model->getOriginalTable().' as '.$alias);
}

// ------------------------------------------------------------------------
// JOIN USING RELATIONSHIPS
// ------------------------------------------------------------------------

/**
* Effectue une jointure en utilisant la relation définie sur le modèle,
* à l'instar de la méthode with().
Expand Down Expand Up @@ -188,10 +181,6 @@ protected function addUpdatedAtColumn(array $values)
return $added ? $values : parent::addUpdatedAtColumn($values);
}

// ------------------------------------------------------------------------
// HELPERS
// ------------------------------------------------------------------------

/**
* Crée et retourne l'instance du JoinRel Builder.
*
Expand Down
36 changes: 35 additions & 1 deletion src/Eloquent/ModelTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,40 @@

trait ModelTrait
{
/**
* Original table when table is replaced by an alias.
*
* @var string|null
*/
private $originalTable = null;

/**
* Get the original table associated with the model.
*
* @return string
*/
public function getOriginalTable()
{
return $this->originalTable ?: $this->getTable();
}

/**
* Create a new instance of the given model.
*
* @param array $attributes
* @param bool $exists
* @param string|null $alias
* @return static
*/
public function newInstance($attributes = [], $exists = false, $alias = null)
{
$instance = parent::newInstance($attributes, $exists);

$instance->originalTable = $this->getOriginalTable();

return $instance->setTable($alias ?: $instance->originalTable);
}

/**
* Returns a new instance of the extended Eloquent Builder.
*
Expand All @@ -22,6 +56,6 @@ public function newEloquentBuilder($query)
*/
public function getOrderBy()
{
return isset($this->orderBy) ? $this->orderBy : null;
return $this->orderBy ?? null;
}
}

0 comments on commit b68e12b

Please sign in to comment.