pmiranda
pmiranda

Reputation: 8470

Laravel, merge two queries in one

How could I do a better code than this one:

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

foreach ($data1 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();
}
$tareas['data1'] = $data1;

// All this bucle takes ~13000 miliseconds

$data2 = UploadsPois::where('estado_carga', Util::UPLOAD_POIS_CARGA_DEVUELTA_REVISION)
    ->where('schema_country', $schema_country)
    ->where('revisado_por', \Auth::user()->id)
    ->orderBy('id', 'asc')
    ->get();

foreach ($data2 as $carga) {
    $carga->UserResponsable = User::findOrFail($carga->responsable);
    $carga->UserValidador   = User::findOrFail($carga->validado_por);
    $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();
}
$tareas['data2'] = $data2;

// And this one takes ~ 20 or 50 miliseconds

Those bucles are pretty the same, how could I merge in one single foreach and 1 single call to UploadsPois model? I'm not sure how could I set $tareas['data1'] and $tareas['data2'] in the same process.

Upvotes: 0

Views: 75

Answers (1)

IGP
IGP

Reputation: 15909

Looking at this code, I can tell there are 4 important models: UploadsPois, User, Pois, LogPois.

You can set up relationships to load all this data without having to loop.

See Eloquent Relationships, Eloquent Relationships: Eager Loading

# UploadPois model
namespace App;

use Illuminate\Database\Eloquent\Model;
use User;
use Pois;
use LogsPois;

class UploadsPois extends Model
{
    public function user_responsable()
    {
        return $this->belongsTo(User::class, 'responsable');
    }

    public function user_validador()
    {
        return $this->belongsTo(User::class, 'validado_por');
    }

    public function pois()
    {
        return $this->hasMany(Pois::class, 'upload_pois_id');
    }

    public function log()
    {
        return $this->hasMany(LogsPois::class, 'upload_pois_id');
    }
}

You can also define the inverse of the relationships as follows.

# User model
namespace App;

// Usually User model extends this instead of base model.
use Illuminate\Foundation\Auth\User as Authenticatable;
use UploadsPois;

class User extends Authenticatable
{
    public function responsable_uploads_pois()
    {
        return $this->hasMany(UploadsPois::class, 'responsable');
    }

    public function validador_uploads_pois()
    {
        return $this->hasMany(UploadsPois::class, 'validado_por');
    }
}
# Pois model
namespace App;

use Illuminate\Database\Eloquent\Model;
use UploadsPois;

class Pois extends Model
{
    public function uploads_pois()
    {
        return $this->belongsTo(UploadsPois::class, 'upload_pois_id');
    }
}
# LogPois model
namespace App;

use Illuminate\Database\Eloquent\Model;
use UploadsPois;

class LogPois extends Model
{
    public function uploads_pois()
    {
        return $this->belongsTo(UploadsPois::class, 'upload_pois_id');
    }
}

Now that we have all relationships defined, your $data1 variable can be obtained as follows:

UploadsPois::where([
    ['estado_carga', Util::UPLOAD_POIS_CARGA_INGRESADA],
    ['schema_country', $schema_country]
])
->with([
    'user_responsable',
    '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();

as for $data2:

UploadsPois::where([
    ['estado_carga', Util::UPLOAD_POIS_CARGA_DEVUELTA_REVISION],
    ['schema_country', $schema_country],
    ['revisado_por', auth()->id()] //Same as \Auth::id(), same as \Auth::user()->id
])
->with([
    'user_responsable',
    'user_validador',
    '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();

Laravel naming conventions dictate your relationship methods must be in snake_case.

About combining those queries. The only differences I see are the following:

  • $data1 has estado_carga equal to Util::UPLOAD_POIS_CARGA_INGRESADA whereas $data2 has estado_carga equal to Util::UPLOAD_POIS_CARGA_DEVUELTA_REVISION
  • $data2 has an additional filter (validado_por equal to authenticated user's id)
  • $data2 has an additional relationship loaded (user_validador)

If you want really want to combine the queries, you could just not filter by those 2 conditions initially.

$data = UploadsPois::where('schema_country', $schema_country)
->with([
    'user_responsable',
    'user_validador',
    '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();

This returns a collection, which you can then filter using a variety of methods (where, firstWhere, filter, reject, etc)

# data1
$data->where('estado_carga', Util::UPLOAD_POIS_CARGA_INGRESADA);
# data2
$data->where('estado_carga', Util::UPLOAD_POIS_CARGA_DEVUELTA_REVISION)->where('validado_por', auth()->id());

See Collections: Available Methods

Upvotes: 1

Related Questions