1

关系定义如下:

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 合并它的关系。

4

1 回答 1

0

第 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');
    }
}

第二步:从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
    ];
});
于 2020-10-12T14:00:44.527 回答