简体   繁体   English

在Laravel的雄辩查询中指定一个select子句

[英]Specifying a select clause in Laravel's eloquent query

Tables

category                 category_path
---------------          ----------------
id                       category_id
title                    path_id
                         level

Queries 查询

    CategoryPath::with('Category')
        ->select('*', DB::Raw('group_concat(title ORDER BY level SEPARATOR " > ") as name'))
        ->groupBy('category_path.category_id')->paginate(10);

I get an error Unknown column 'title' in group_concat . 我在group_concat收到错误Unknown column 'title'

How can I make selections from the related table? 如何从相关表格中进行选择?

Simple Solution: 简单解决方案

Use model class instead of DB class then query will maintain eloquent relationships: 使用模型类而不是DB类,然后查询将保持雄辩的关系:

$categories = CategoryPath::select('*', DB::Raw('group_concat(title ORDER BY level SEPARATOR " > ") as name'))
    ->leftJoin('category', 'category_path.path_id', '=', 'category.id')
    ->groupBy('category_path.category_id')
    ->orderBy('name', 'ASC')
    ->paginate(10);

You could use the lists() method. 您可以使用lists()方法。

$categoryPath = CategoryPath::with('category')->paginate(10);

foreach($categoryPath as $path) {
    echo implode(' > ', $path->category->lists('title'));
}

That should have the desired affect, although I am making some assumptions. 虽然我做了一些假设,但这应该会产生预期的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel Eloquent:多重选择和where子句查询 - Laravel Eloquent : multiple select and where clause query 将简单的嵌套选择查询转换为Laravel的口才查询 - Converting simple nested select query to Laravel's Eloquent query Laravel / Eloquent-查询-按关系选择 - Laravel/Eloquent - Query - Select with relationship 使用Laravel Eloquent查询Where子句 - Where clause query using Laravel Eloquent Laravel雄辩的SQL查询与OR和AND与where子句 - Laravel eloquent SQL query with OR and AND with where clause 使用orwhere子句的Laravel雄辩的Orm查询 - Laravel eloquent orm query using orwhere clause 使用Laravel的雄辩的查询构建 - Query building with Laravel's Eloquent 如何构建雄辩的查询以检索主表的记录,在Laravel 5 PHP中对其相关表应用where子句? - How to build Eloquent query to retrieve records of the main table, applying where clause on it's related table in Laravel 5 PHP? Laravel - 使用“with”和“where”子句查询 select - Laravel - query to select with “with” and “where” clause Laravel Eloquent / Query Builder中LEFT JOIN的ON子句中的参数化查询绑定 - Parameterized query binding in ON clause for a LEFT JOIN in Laravel Eloquent / Query Builder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM