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

408 views Asked by At

Relations are as defined below:

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

On querying Rfid::with('logs.reader.department')->get() is giving result as follows:

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},
             },
           ],
         },
       },...

However, I want its relations to be merged using apiresources.

1

There are 1 answers

0
IGP On BEST ANSWER

Step 1: Define a ComponentLog -> Rfid belongsTo relationship

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

Step 2: Get the results from ComponentLog to avoid hasMany relationships

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

Step 3: Map the results

$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
    ];
});

You can also do it inline.

$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
    ];
});