Laravel 5.6 与 whereHas 的多态关系

Laravel 5.6 Polymorphic relation with whereHas

我在多态关系中遇到一个问题,我无法使 whereHas 起作用。基本上我有一个 "where" 我想申请的条件。 关系代码对 return 相关模型工作正常,但一旦应用 whereHas.returns 错误。

下面是代码

订单Class:

class Order extends Model
 {

  // function to return orders 
  public static function getAllOrders()
  { 


    return $orders = Order::with('part.pcategory')->whereHas('part', function ($query) 
         {
                  $query->where('cat_id',4);
         })->get();
  }

  // the relation 
  public function part()
  { 

  return $this->morphTo(null,'department_short_code','part_stock_number','stock_number', 'dep_short_code');
  }

 }

SFD 零件 Class:

class sfd_part extends Model
{

  public function orders()
    {   

    return  $this->morphMany('App\Order','part','department_short_code','part_stock_number');
   }

   public function pcategory()
    {

    return $this->belongsTo('App\Pcategories','cat_id', 'category_id');
    }

}

当我调用 getAllOrders() 时出现以下错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cat_id' in 'where clause' (SQL: select count(*) as aggregate from orders where exists (select * from orders as laravel_reserved_0 where laravel_reserved_0.id = laravel_reserved_0.part_stock_number and cat_id = 2 and laravel_reserved_0.id = laravel_reserved_0.part_stock_number and cat_id = 2))

数据库table结构

我试图获取的数据是一个订单列表,每个部分都相关。然后我得到与这部分相关的类别名称。我还想通过使用 whereHas 来过滤此列表,例如我得到的所有订单来自特定类别 which.

Orders table 有部分链接的订单。这部分可以在 3 个 table 中的任何一个中,这就是为什么我在两个键 department_short_code 和 part_stock_number

上使用多态关系中继

使用 whereHas 时出现了一些问题,我不知道为什么。这种情况可以用其他方式处理

you might not find where method in the editors but it can be used and it works accordingly. use tosql() to further check the query.

Order::with('part.pcategory')->where( function ($query) {
        $query->whereIn('part_id', function ($query) {
            $query->select('id')
                ->from('sfd_part')
                ->where('cat_id',4);
        });
    })->get();

您可以安全干净地使用以下代码。您已用完 Eloquent,但仍在使用 laravel 功能。

Order::with('part.pcategory')
    ->leftJoin('sfd_parts','orders.part_id','=','sfd_parts.id')
    ->where('orders.part_type','=',sfd_parts::class)
    ->where('sfd_parts.cat_id','=',4)
    ->get();