如何在查询中为 eloquent 模型设置别名
How to alias eloquent models in a query
如何为 eloquent 模型起别名?例如,如果我有一个 SQL 查询如下:
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
....
在我的存储库中,我会有如下内容:
$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'));
那么你怎么给模型起别名。在上面的示例中,模型映射位置 table,在我的 eloquent 查询中,我想将其别名为 one
而不是 locations
您可以这样使用from
:
$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'));
如何为 eloquent 模型起别名?例如,如果我有一个 SQL 查询如下:
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
....
在我的存储库中,我会有如下内容:
$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'));
那么你怎么给模型起别名。在上面的示例中,模型映射位置 table,在我的 eloquent 查询中,我想将其别名为 one
而不是 locations
您可以这样使用from
:
$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'));