首页 > 解决方案 > 两个 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"
     }
    ]
  }
]

标签: phplaravel

解决方案


你可以做

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()应该给你你想要的格式。


推荐阅读