【问题标题】:How to return columns and joined columns in a certain order (Eloquent)如何按特定顺序返回列和连接列 (Eloquent)
【发布时间】:2017-03-17 17:35:05
【问题描述】:

我有以下代码:

    Incident::where('id','<','35')->with('priority')->paginate(15);

现在这会返回以下内容: ID、标题、描述、priority_id 和优先级对象。

我想只检索 ID、标题和优先级对象,没有描述或 priority_id,但我希望它们按特定顺序排列,如下所示: ID、优先级和头衔。

但是当我执行以下操作时:

    Incident::where('id','<','5')->with('priority')->paginate(15, array('id', 'priority', 'title'));

我收到一条错误消息,提示未找到列事件。优先级。

当通过 FK 引用其中一个列时,是否有任何方法可以仅选择我想要的列并按照我想要的顺序?

谢谢!

【问题讨论】:

标签: laravel eloquent query-builder


【解决方案1】:

您无需在列表中包含priorityIncident::where('id','&lt;','5')-&gt;with('priority')-&gt;paginate(15, array('id', 'title'));

【讨论】:

  • 但是我不会在我想要的地方获得优先权:'(
  • @SofiaGilardino,你能告诉我你对退回的收藏品做了什么吗?
【解决方案2】:

如果您将回调传递给with 方法,您可以像这样指定顺序:

Incident::where('id','<','35')
    ->with(['priority' => function ($query) {
        $query->select('id', 'priority', 'title');
    }])
    ->paginate(15);

【讨论】:

    【解决方案3】:

    您的查询不是联接。 with('priority') 实际上是第二个单独的查询,在 Incident 查询之后执行,然后附加到 Incident 模型。如果您想引用列并使用连接,您可以这样做:

    Incident::select('id', 'priorities.*', 'incidents.title')
        ->leftJoin('priorities', 'priorities.id', '=', 'incidents.priority_id')
        ->where('incidents.id', '>', '5')
        ->paginate(15);
    

    如果您不想使用上述方法,那么@tam 答案将是最好的,但请确保使用他的解决方案在子查询回调中包含 id,因为这是关系在之后将自身附加到父模型的方式查询已运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 2023-02-10
      • 2019-02-03
      相关资源
      最近更新 更多