mercredi 9 octobre 2019

Laravel, relation comes empty

(Laravel 5.3) I had a code that assign a property to a collection (UploadsPois), in a foreach loop. It was this one:

$data= UploadsPois::where('estado_carga', Util::UPLOAD_POIS_CARGA_INGRESADA)
    ->where('schema_country', $schema_country)
    ->orderBy('id', 'asc')
    ->get();

foreach ($data as $carga) {
    $carga->UserResponsable = User::findOrFail($carga->responsable);
    $carga->Pois            = Pois::where('upload_pois_id', $carga->id)->where('pois_validate', Util::POIS_INGRESADO)->orderBy('id', 'asc')->get();
    $carga->Log = LogsPois::where('upload_pois_id', $carga->id)
        ->where('schema_country', $schema_country)
        ->whereNull('address_id')
        ->orderBy('id', 'desc')
        ->first(); //  HERE I HAVE A PROBLEM
}

That code was dumb and slow, but was working ok. My data was well retrieved (check the image below). I could use the data on my view to read it in some part like this:

@foreach($data as $carga)

    @if(is_object($carga->Log))
        //do something with
        $carga->Log->comentario

Now, with the help of @IGP and @Tim Lewis (Laravel, merge two queries in one) I replaced that foreach with the use of relations on my UploadsPois model.

UploadsPois mode has this relations:

public function UserResponsable()
{
    return $this->belongsTo('App\User', 'responsable');
}

public function Pois()
{
    return $this->hasMany('App\Pois', 'upload_pois_id');
}

public function Log()
{
    return $this->hasMany('App\LogsPois', 'upload_pois_id');
}

And now the code on the controller is:

$data = UploadsPois::where([
    ['estado_carga', Util::UPLOAD_POIS_CARGA_INGRESADA],
    ['schema_country', $schema_country]
])
    ->with([
        'UserResponsable',
        'Pois' => function ($pois) {
            $pois->where('pois_validate', Util::POIS_INGRESADO);
        },
        'Log' => function ($log) use ($schema_country) {
            $log->where('schema_country', $schema_country)
                ->whereNull('address_id')
                ->orderBy('id', 'desc');
        }
    ])
    ->orderBy('id', 'asc')
    ->get();

But I have two problems now:

  • First, Log relation is getting empty. The problem I think is with the ->first() that is being omitted in the ->with([]) part.
  • In my view, I can't acces to $data->Log anymore because now Log, Pois and UserResponsable aswell are not attributes, but their are relations.

Here is a screenshot of the dd($data->first()); with the old code and the new one with relations: (UPDATING THE IMAGE) enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire