【问题标题】:Laravel Eager Loading Order By date/other fields and last record inside the relationshipLaravel Eager Loading Order By date/other fields and last record in the relationship
【发布时间】:2015-04-07 10:47:11
【问题描述】:

我有 3 个带有字段的模型

LEAD
    id
    first_name
    surname

//in lead model
public function trxn()
{
    return $this->hasMany('lead_trxn', 'lead_id', 'id');
}

LEAD_TRXN
    id
    lead_id
    create_datetime
    expiration_datetime
    status

//in lead_trxn model
public function detail()
{
    return $this->hasMany('lead_trxn_details', 'lead_trxn_id', 'id');
}

LEAD_TRXN_DETAILS
    id
    lead_trxn_id
    product_id
    create_datetime
    status

我有这个使用急切加载检索记录

$leads = Lead::with(
                    array
                         (
                             'trxn' => function($qry)
                             {
                                 $qry->with(
                                               array
                                               (
                                                   'details'
                                                   //i need the last inserted product here
                                               )
                                           );

                                  //i need to order it by expiration date
                                  //$qry->orderBy('expiration_date');
                             }
                         )
                   )->get();

问题 1: 如何按到期日期或在lead_trxn 中的create_datetime 对其进行排序,以使其成为动态过滤器?意思是,如果我将数据绘制到表格中,然后单击表格的标题,它将根据我单击的标题对记录进行排序。

问题 2: 如何获取最后插入到lead_trxn_details 中的product_id?

非常感谢您的帮助。谢谢。

【问题讨论】:

  • 1 joins 是唯一的方法,2 不确定你的意思,但我想这就是你想要的 softonsofa.com/…

标签: laravel eloquent eager-loading


【解决方案1】:

由于您从用户那里获得了列顺序和方向,因此您需要将列和方向都传递到查询中。因此,您可以在闭包内使用orderBy 函数扩展查询。

   $leads = Lead::with(array( 'trxn' => function($qry) use($orderByColumn, $direction) {
      $qry->orderBy($orderByColumn, $direction)
        ->with( array ( 'details' => function($q) {
            $q->orderBy('create_datetime', 'desc')->first(); // get the latest inserted product
          })
      );
    }
  )
 )->get();

【讨论】:

  • 如果我想按升序排序呢?或者我可以在问题 1 中添加要求吗?如果我想在lead_trxn 中添加更多过滤器怎么办?抱歉,我想我之前忘记指定了。
  • @Ponce 我更新了我的代码。请尝试并告诉我。
  • @Ponce 我想我已经为这两个问题找到了解决方案。请尝试让我知道结果。 :)
猜你喜欢
  • 2020-11-09
  • 2020-11-11
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
相关资源
最近更新 更多