简体   繁体   English

Laravel,将两个查询合二为一

[英]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?那些 bucles 几乎一样,我如何合并一个 foreach 和一个对UploadsPois model 的单个调用? I'm not sure how could I set $tareas['data1'] and $tareas['data2'] in the same process.我不确定如何在同一过程中设置$tareas['data1']$tareas['data2']

Looking at this code, I can tell there are 4 important models: UploadsPois , User , Pois , LogPois .查看这段代码,我可以看出有 4 个重要模型: UploadsPoisUserPoisLogPois

You can set up relationships to load all this data without having to loop.您可以设置关系以加载所有这些数据,而无需循环。

See Eloquent Relationships , Eloquent Relationships: Eager Loading请参阅Eloquent 关系Eloquent 关系:急切加载

# 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:现在我们已经定义了所有关系,您的$data1变量可以如下获得:

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 :至于$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. Laravel 命名约定规定您的关系方法必须采用蛇形大小写。

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 $data1estado_carga等于Util::UPLOAD_POIS_CARGA_INGRESADA$data2estado_carga等于Util::UPLOAD_POIS_CARGA_DEVUELTA_REVISION
  • $data2 has an additional filter ( validado_por equal to authenticated user's id ) $data2有一个额外的过滤器( validado_por等于经过身份验证的用户的id
  • $data2 has an additional relationship loaded ( user_validador ) $data2加载了一个附加关系( 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)这将返回一个集合,然后您可以使用各种方法( wherefirstWherefilterreject等)对其进行过滤

# 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请参阅Collections:可用方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM