Last active
March 25, 2021 16:01
-
-
Save mattsplat/9325b089633596fe6b9360fc0e3c5c83 to your computer and use it in GitHub Desktop.
withAttached
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
/** | |
* | |
* Usage | |
* | |
* Register in provider | |
* Builder::mixin(new WithAttachedMixin); | |
* | |
* withAttached( | |
* relation name, | |
* name of property (default = {relation_name}_{column}s), | |
* subquery callback (default = null), | |
* column name (default = id) | |
* ) | |
* | |
$u = App\User::withAttached( | |
'groups', | |
'group_list', | |
function($q) { | |
$q->where('id', '>', 15); | |
}, | |
'id' | |
)->find(7); | |
$u->group_list; // = [16,22,25,29] | |
*/ | |
use Illuminate\Database\Query\Expression; | |
class WithAttachedMixin | |
{ | |
public function withAttached() { | |
return function( | |
$relationName, | |
$alias = null, | |
$subQuery = null, | |
$column = 'id' | |
) { | |
if (is_null($this->query->columns)) { | |
$this->query->select([$this->query->from.'.*']); | |
} | |
$relation = $this->getRelationWithoutConstraints($relationName); | |
// prepare group concat statement | |
$expression = "concat( '[', GROUP_CONCAT($column SEPARATOR ',' ),']')"; | |
$query = $relation->getRelationExistenceQuery( | |
$relation->getRelated()->newQuery(), $this, new Expression($expression) | |
)->setBindings([], 'select'); | |
if ($subQuery !== null) { | |
$query->callScope($subQuery); | |
} | |
$query = $query->mergeConstraintsFrom($relation->getQuery())->toBase(); | |
if (count($query->columns) > 1) { | |
$query->columns = [$query->columns[0]]; | |
} | |
if ($alias === null) { | |
$alias = $relationName."_".$column."s"; | |
} | |
$this->model->mergeCasts([$alias => 'array']); | |
$this->selectSub($query, $alias); | |
return $this; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment