在laravel中加入find_in_set

时间:2019-10-11 05:35:32

标签: laravel laravel-5

如何使用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('')));
});

2 个答案:

答案 0 :(得分:0)

我不知道您当前面临的确切Laravel语法问题,但是当前的左联接逻辑存在潜在的问题。如果给定的用户有多本匹配的书,那么他将在每次匹配中一次出现在结果集中。大概这不是您想要的,所以我建议使用EXISTS逻辑加入:

SELECT u.id, u.name
FROM User u
WHERE EXISTS (SELECT 1 FROM Books b WHERE FIND_IN_SET(b.id, u.b_id) > 0);

Laravel代码:

$res = DB::table('user u')
    ->whereExists(function ($query) {
        $query->select(DB::raw(1))
              ->from('book b')
              ->whereRaw('FIND_IN_SET(b.id, u.b_id) > 0');
        })
    ->get();

existing方法可确保每个用户在结果集中只会出现一次。

答案 1 :(得分:0)

尝试一下。

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

        )

)