As an alias for eloquent patterns in a query

How do you feel about the 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 will have something like this:

$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 use a model alias. In the above example, the model displays a table of locations and in my eloquent query I want to use it as oneinsteadlocations

+4
source share
1 answer

You can use fromas follows:

$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'));
+7
source

Source: https://habr.com/ru/post/1628647/


All Articles