【发布时间】:2020-02-06 19:37:48
【问题描述】:
(Laravel 5.3) 我有一个代码在 foreach 循环中将属性分配给集合 (UploadsPois)。就是这个:
$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
}
该代码既笨又慢,但运行正常。我的数据得到了很好的检索(检查下图)。我可以使用视图上的数据来读取它,如下所示:
@foreach($data as $carga)
@if(is_object($carga->Log))
//do something with
$carga->Log->comentario
现在,在@IGP 和@Tim Lewis (Laravel, merge two queries in one) 的帮助下,我用UploadsPois 模型上的关系替换了那个foreach。
UploadsPois模式有这样的关系:
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');
}
现在控制器上的代码是:
$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');
//NOW I'm not calling ti ->first(), so I get the whole collection, but when I use first I get an empty collection
}
])
->orderBy('id', 'asc')
->get();
但是我现在有两个问题:
- 首先,
Log关系正在获取 3 个项目的集合。我认为问题在于->first()在->with([])部分中被省略了。 - 在我看来,我无法再访问
$data->Log,因为现在Log、Pois和UserResponsable也不是属性,而是关系。
这是dd($data->first()); 的屏幕截图,带有旧代码和带有关系的新代码:
【问题讨论】:
-
完成,不再编辑。
标签: laravel laravel-5 eloquent