我们如何使用 apiresources laravel 将多个关系合并到一维数组中

how can we merge multiple relation into one dimensional array using apiresources laravel

关系定义如下:

class Rfid extends Model
{
    use HasFactory;

    public function logs()
    {
        return $this->hasMany('App\Models\ComponentLog', 'rfid_id');
    }
}

class ComponentLog extends Model
{
    use HasFactory;

    public function reader()
    {
        return $this->belongsTo('App\Models\RfidReader','rfid_reader_id');
    }
}

class RfidReader extends Model implements AuthenticatableContract
{
    use HasFactory;
    use HasApiTokens;
    use Authenticatable;

    public function department()
    {
        return $this->belongsTo('App\Models\Department', 'department_id');
    }
}

查询 Rfid::with('logs.reader.department')->get() 给出的结果如下:

App\Models\Rfid {#4554
         id: 13,
         RFID: "KDtCgimCJJ",
         department_id: 6,
         component_id: 13,
         created_at: "2020-10-12 10:48:32",
         updated_at: "2020-10-12 10:48:32",
         logs: Illuminate\Database\Eloquent\Collection {#4599
           all: [
             App\Models\ComponentLog {#4576
               id: 13,
               rfid_id: 13,
               check_in: "2020-10-12 10:48:32",
               check_out: null,
               rfid_reader_id: 4,
               created_at: null,
               updated_at: null,
               reader: App\Models\RfidReader {#4421},
             },
           ],
         },
       },...

但是,我希望使用 apiresources 合并它的关系。

第 1 步:定义一个 ComponentLog -> Rfid belongsTo 关系

class ComponentLog extends Model
{
    use HasFactory;

    public function reader()
    {
        return $this->belongsTo('App\Models\RfidReader','rfid_reader_id');
    }

    public function rfid()
    {
        return $this->belongsTo('App\Models\Rfid', 'rfid_id');
    }
}

第 2 步:从 ComponentLog 中获取结果以避免 hasMany 关系

$logs = ComponentLog::with(['rfid', 'reader.department'])->get();

第 3 步:映射结果

$logs->transform(function ($log) {
    return [
        'rfid' => $log->rfid->rfid,
        'department_name' => $log->reader->department->department_name,
        'rfid_reader_id' => $log->rfid_reader_id,
        'check_in' => $log->check_in,
        'check_out' => $log->check_out
    ];
});

您也可以在线执行此操作。

$logs = ComponentLog::with(['rfid', 'reader.department'])
->get()
->transform(function ($log) {
    return [
        'rfid' => $log->rfid->rfid,
        'department_name' => $log->reader->department->department_name,
        'rfid_reader_id' => $log->rfid_reader_id,
        'check_in' => $log->check_in,
        'check_out' => $log->check_out
    ];
});