【问题标题】:how to retrieve all stations from a query with many related tables using Laravel Eloquent?如何使用 Laravel Eloquent 从具有许多相关表的查询中检索所有站点?
【发布时间】:2017-11-21 13:50:35
【问题描述】:

我有以下查询来检索所有与车站相关的表,表 estacion(station) 总共有 55 条记录。使用下面的代码,我只检索与其他表相关的数据的记录。一个站是否有相关数据我也需要显示所有 55 个站。我尝试了使用 leftJoin 的查询构建器,但与使用 Eloquent 相比,查询太大了。

  $ficha = Estacion::select('estacion.*')
                        ->with('titular')
                        ->with('operador')
                        ->with('estacionestado')
                        ->with('comuna')
                        ->with('eqestacion')
                        ->with('equipos.parametros')
                        ->where('estacion.id',$value)
                        ->get();    

我现在得到什么。

【问题讨论】:

  • 永远不要在后端编写除英语以外的其他语言。前端用户看不到的东西应该总是用英语。原因: 1. 其他人可以从事该项目。 2. 更容易得到别人的帮助。

标签: laravel eloquent


【解决方案1】:

你去吧:

$ficha = Estacion::with('titular',
                        'operador',
                        'estacionestado',
                        'comuna',
                        'eqestacion',
                        'equipos.parametros')
                        ->where('id',$value)
                        ->get();

这将为所有站点提供相关数据。其中estacion.id / id 等于$value

如果这不起作用,要么您在比较错误的$value,否则您的关系设置不正确。

【讨论】:

  • 返回一模一样的数据,1个站加上相关表数据,目前大部分站都没有titular和operador的相关数据。
  • @RodrigoCabrera 没关系,即使关系数据为空,它也会始终返回所有站点。
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 2015-07-25
  • 1970-01-01
  • 2020-01-06
  • 2015-06-25
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
相关资源
最近更新 更多