具有Eloquent ORM的单个表列的多个别名

时间:2015-01-15 08:32:52

标签: php laravel eloquent

是否可以从单个表列中获得多个别名。如果我在MySQL中执行以下操作,我会得到我想要的结果:

SELECT name, name AS label, name AS value FROM `tags` WHERE 1 

但是,如果我尝试这样做:

$query->select('name, name AS label, name AS value');

..它告诉我SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name,' in 'field list' (SQL: select名称,as AS from代码where代码. deleted_at is null group by名称order by名称asc)

如果我尝试

$query->select('name AS name, name AS label, name AS value');

..它不会抛出错误,而是只给我一个别名(名称)。如何使用Eloquent ORM实现这一目标?感谢

2 个答案:

答案 0 :(得分:1)

当您尝试选择laravel时,请执行以下操作:

public function select($columns = array('*'))
{
    $this->columns = is_array($columns) ? $columns : func_get_args();

    return $this;
}

当你传递弦乐时,laravel认为你传递了几个args,所以你可以这样做:

$query->select(['name AS name', 'name AS label', 'name AS value']);

或者

$query->selectRaw('name AS name, name AS label, name AS value'):

或者

$query->select(DB::raw('name AS name, name AS label, name AS value'));

或者像@Jarek Tkaczyk说的那样

$query->select('name as name', 'name as label', 'name as value');

答案 1 :(得分:0)

试试这个:

$query->select(DB::raw('name AS name, name AS label, name AS value'));

Link of Laravel Doc