Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel根据日期/其他字段和关系中的最后一条记录急切加载订单_Laravel_Eloquent_Eager Loading - Fatal编程技术网

Laravel根据日期/其他字段和关系中的最后一条记录急切加载订单

Laravel根据日期/其他字段和关系中的最后一条记录急切加载订单,laravel,eloquent,eager-loading,Laravel,Eloquent,Eager Loading,我有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_

我有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中创建_datetime?也就是说,如果我将数据打印到一个表中,然后单击表的标题,它将根据我单击的标题对记录进行排序

问题2: 如何获取lead\u trxn\u详细信息中插入的最后一个产品\u id


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

因为您从用户那里获得了列顺序和方向,所以需要将列和方向都传递到查询中。因此,您可以在闭包中使用
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我想我对这两个问题都找到了答案。请试着告诉我结果。:)1
连接是唯一的方法,2不确定你的意思,但我想这就是你想要的