Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias eloquent models in a query

How do you alias an eloquent model? For example if I have an SQL query as follows:

SELECT one.name
     , one.id
     , one.name AS sortkey1
     , CAST(NULL AS UNSIGNED) AS sortkey2
     , CAST(NULL AS UNSIGNED) AS sortkey3
 FROM locations AS one
WHERE one.parent_id = 0
UNION ALL
....

In my repository I would have something as follows:

$first = $this->model->where('one.parent_id', '=', 0)
                     ->select('one.name'
                           , 'one.id'
                           , 'one.name AS sortkey1'
                           , DB::raw('CAST(NULL AS UNISIGNED) AS sortkey2')
                           , DB::raw('CAST(NULL AS UNISIGNED) AS sortkey3'));

So how can you alias the model. In the above example the model maps the the locations table and in my eloquent query I want to alias it as one instead of locations

like image 218
adam78 Avatar asked Mar 14 '23 07:03

adam78


1 Answers

You can use from this way:

$first = $this->model->from('locations as one')
                     ->where('one.parent_id', '=', 0)
                     ->select('one.name'
                           , 'one.id'
                           , 'one.name AS sortkey1'
                           , DB::raw('CAST(NULL AS UNISIGNED) AS sortkey2')
                           , DB::raw('CAST(NULL AS UNISIGNED) AS sortkey3'));
like image 55
Marcin Nabiałek Avatar answered Mar 16 '23 16:03

Marcin Nabiałek