laravel ORM 如何将with关联的数据放在平级
1. 运行环境
1). 当前使用的 Laravel 版本?
8.83.11
2). 当前使用的 php/php-fpm 版本?
PHP 版本:
PHP 7.3.4
2. 问题描述?
达成效果的代码为:
return self::where('user_id', $userId)->leftJoin('dispatch', 'dispatch_user_rule.dispatch_id', '=', 'dispatch.id')
->select(['dispatch.id', 'name', 'dispatch.created_at'])->get();
内容
[
{
"id": 1,
"name": "滴答集团",
"createdAt": "2022-05-13 15:08:43"
},
{
"id": 2,
"name": "嘀嗒拼车",
"createdAt": "2022-05-16 10:51:31"
}
]
使用ORM的with:
return self::where('user_id', $userId)->with('dispatch')->get();
目前得到的结果
[
{
"id": 1,
"userId": 1,
"dispatchId": 1,
"createdAt": "2022-05-13 15:08:54",
"updatedAt": "2022-05-13 15:08:56",
"dispatch": {
"id": 1,
"name": "滴答集团",
}
},
{
"id": 3,
"userId": 1,
"dispatchId": 2,
"createdAt": "2022-05-16 10:51:50",
"updatedAt": "2022-05-16 10:51:52",
"dispatch": {
"id": 2,
"name": "嘀嗒拼车",
}
}
]
最近才上手laravel,迫于代码洁癖不想混用DB库,问问各位大神这个在ORM中正确的写法是什么?
推荐文章: