首页 > 解决方案 > 在 laravel 中加入 find_in_set

问题描述

如何使用 laravel 查询获得期望的输出。试过这种方法没有成功,请提前指导非常感谢

如果可能的话,有什么方法可以在模型中设置它,请指导

User

id  name    b_id
1   Alax    1,3
2   Rex     2,4
3   Lex     2,3

Books

id  book_name   book_author
1   Javascript  jim
2   PHP         json
3   LARAVEL     rax
4   SYMPHONY    Alax

Output

id  name    b_id
1   Alax    Javascript, LARAVEL
2   Rex PHP, SYMPHONY
3   Lex PHP, LARAVEL

和查询:

$res = DB::table('user')->leftJoin('book', function($join){
   $join->on(DB::raw("find_in_set(book.id, user.b_id)",DB::raw(''),DB::raw('')));
});

标签: laravellaravel-5

解决方案


尝试这个。

$data = \DB::table("user")
        ->select("user.*",\DB::raw("GROUP_CONCAT(book.book_name) as book_name"))
        ->leftjoin("book",\DB::raw("FIND_IN_SET(book.id,user.b_id)"),">",\DB::raw("'0'"))
        ->get();


\DB::raw("GROUP_CONCAT(CONCAT(book.book_name, ' - ', book.book_author) SEPARATOR ', ') AS book_name_author")

你的输出看起来像。

Illuminate\Support\Collection Object

(

    [items:protected] => Array

        (

            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => Alax
                    [b_id] => 1,3
                    [book_name] => Javascript,LARAVEL
                )

            [1] => stdClass Object
                (
                    [id] => 2
                    [name] => Rex
                    [b_id] => 2,4
                    [book_name] => PHP,SYMPHONY
                )
            [2] => stdClass Object
                (
                    [id] => 3
                    [name] => Lex
                    [b_id] => 2,3
                    [book_name] => PHP,LARAVEL
                )

        )

)

推荐阅读