【问题标题】:Laravel Eloquent whereHas IssueLaravel Eloquent whereHas 问题
【发布时间】:2020-06-21 16:42:07
【问题描述】:

我正在尝试在我的最后一行 HasMany 关系上使用 Laravel Eloquent whereHas 来查找上次更新状态但是这个查询让我所有的操作都没有顺序。 我看到 this 。我想在 lastAction 上使用 where 查询,这对我不起作用。谢谢

我的 Order.php 文件

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table = "orders";
    protected $guarded = [];
    
    public function action()
    {
         return $this->hasMany(OrderAction::class, 'order_id');
    }
}

我的 OrderController.php 文件

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $items = Order::where(function ($query) use ($request) {
            if ( !empty($request->filter_status )) {
                $query->whereHas('action',function($query1) use ($request){
                    $query1->where('state_to',$request->filter_status);
                });
            }})->latest('id')->paginate(20);

        $items->appends($request->query());
        return view('order.index',compact('items'));
    }
}

【问题讨论】:

  • 如果您想按关系订购,我相信您需要使用联接。否则,它将始终按最新 ID 订购您的订单。看看这个:stackoverflow.com/questions/48321076/…
  • 解释你想要什么?
  • 我想通过 orderAction 表中最后添加的行中的 state_to 字段过滤订单,因为我的订单最后状态存储在那里
  • $items = Order::when(isset($request->filter_status),function($query)use($request){ $query->select('orders.*', DB: :raw('(select state_to from order_action where orders.id = order_action.order_id order by id desc limit 1) as state_to ' ) ); $query->where('state_to',$request->filter_status); })- >latest('id')->get();此代码返回未知列 state_to

标签: php laravel eloquent


【解决方案1】:

应该这样做(您可能需要调整代码以适应您的应用程序):

$items = Order::when(isset($request->filter_status), function($query) use ($request) { 
   $orderActions = OrderAction::selectRaw('MAX(id), state_to')
       ->groupBy('order_id');

   $query->joinSub($orderActions, 'order_actions', function ($join) {
       $join->on('orders.id', '=', 'order_actions.order_id');
     }) 
     ->where('state_to', $request->filter_status);  
 })
 ->latest('id')
 ->paginate(20);

参考: https://laravel.com/docs/7.x/queries#joins - 子查询连接

【讨论】:

  • 此代码返回错误,我用 groupby() 修复它,但结果没有差异,仍然是一个问题
  • SQLSTATE[42S02]:未找到基表或视图:1146 表 'offtapp_api.select max(id), state_to from order_action' 不存在(SQL:选择计数(*)为从orders 聚合内部连接select MAX(id), state_to from ``order_action``` on order_id` = orders.id 其中state_to = 取消)
  • 能否请您尝试更改查询->加入查询->joinSub($rawQuery, 'order_actions', function($join){ $join->on('order_actions.order_id', 'orders .id'); })
  • 谢谢,我没有找到答案,但我找到了答案,如果我可以选择 max(id) 行的 state_to 并将其分组(获取最后一个),我会得到答案跨度>
猜你喜欢
  • 1970-01-01
  • 2021-08-23
  • 2019-12-28
  • 2017-06-09
  • 2020-09-16
  • 2014-09-30
  • 2020-12-23
  • 2021-05-25
  • 2018-06-19
相关资源
最近更新 更多