简体   繁体   中英

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 .

How can I make selections from the related table?

Simple Solution:

Use model class instead of DB class then query will maintain eloquent relationships:

$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.

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM