laravel - 在 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('')));
});
解决方案
尝试这个。
$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
)
)
)
推荐阅读
- elasticsearch - 使用 pfx 拆分为单独的证书和密钥时,Elasticsearch 因 PEM 证书错误而崩溃
- lua - 如何在另一个脚本中调用服务器事件?
- wordpress - Nginx 斜杠重定向 wp-admin - 可能是代理问题
- powershell - 如何使用 powerhell 启动已安装的服务并设置该服务的启动类型
- python - 用于多个流的python twitch聊天记录器
- javascript - 为什么我的 else-if Javascript 条件不起作用?
- python - 如何在 Django 中使用自动生成的 slug 作为发布 URL 链接
- css - Tailwind CSS 自定义断点不起作用
- php - spatie/laravel-analytics pageViews 在增加时间段时越来越多,即使页面是几天前的
- json - 如何从外部 API 访问 Json 字符串值?