如何在查询中为 eloquent 模型起别名
Posted
技术标签:
【中文标题】如何在查询中为 eloquent 模型起别名【英文标题】:How to alias eloquent models in a query 【发布时间】:2016-05-24 18:16:11 【问题描述】:你如何给一个雄辩的模型起别名?例如,如果我有如下 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'));
那么,如何给模型起别名。在上面的示例中,模型映射了位置表,并且在我雄辩的查询中,我想将其别名为 one
而不是 locations
【问题讨论】:
【参考方案1】:你可以这样使用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 模型起别名的主要内容,如果未能解决你的问题,请参考以下文章
Rails 4 - 如何在活动记录查询中为包含()和连接()提供别名