php - 两个 Laravel 子查询(一个模型两个关系)
问题描述
我想问是否有一种方法可以使用 with() 为一个模型获取两个子查询。
电脑型号:
class Computer extends Model {
public function user() {
return $this->belongsTo('\App\User');
}
}
模型用户:
class User extends Model {
public function department() {
return $this->belongsTo('\App\Department');
}
public function roles() {
return $this->hasMany('\App\Role');
}
}
询问:
Computer::where("pc_no" $request->pc_no)->with(["user.[department, roles]"]);
输出需要:
{
computer: [
{
id: 1,
name: "PC1"
department: {
id: 1,
name: "Encoding"
},
roles: [
{
id: 1,
name: "Typist"
},
{
id: 2,
name: "Filer"
}
]
}
]
解决方案
你可以做
Computer::where("pc_no", $request->pc_no)
->with(["user.department", "user.roles"])
->get();
这会给你带来类似的东西
{
computer:
[
{
id: 1,
name: "PC1"
user:
{
department:
{
id: 1,
name: "Encoding"
},
roles:
[
{
id: 1,
name: "Typist"
},
{
id: 2,
name: "Filer"
}
]
}
}
]
]
如果您不想要用户部分,您可能需要使用 Eloquent Resource。您可以使用命令从控制台创建一个
php artisan make:resource Computer
然后,使 ToArray 方法如下:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Computer extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'department' => $this->user->department,
'roles' => $this->user->roles,
// Any other param you want in your json/array should be set here explicitly
];
}
}
最后,调用在你的控制器中使用该资源。
use App\Http\Resources\Computer as ComputerResource;
...
$computer = Computer::where("pc_no", $request->pc_no)
->with(["user.department", "user.roles"])
->get();
$computer_resource = new ComputerResource($computer);
$computer_resource->toArray()
应该给你你想要的格式。
推荐阅读
- r - ggplot构面图重新排序未按预期工作
- algorithm - 我正在努力为我的家庭作业找到有效的解决方案。冒泡排序还是插入排序?
- php - php - 基于范围键返回数组
- kubernetes - 将 2 个不同的 statefulSet 连接到同一个 PV
- architecture - 在 DDD 的上下文中应该如何处理事务
- ruby-on-rails - 更新具有相同图像的模型时出现 ActiveSupport::MessageVerifier::InvalidSignature 错误
- git - 在 Git 中将分支从主分支移动到另一个分支
- c# - 用 C# 编写其他语言时的输入问题
- android - OpenTok 库的视频质量问题
- python - Django ManyToMany 字段给出 IntegrityError