0

您好我正在尝试使用十月 CMS 活动记录实现进行组合查询,以过滤掉用户选择的输入。

有四个模型 a Color, Series, DepartmentProduct其关系如下:

Product型号_

public $belongsTo = [
  'color' => 'depcore\parts\Models\Color',
];


public $belongsToMany = [
  'series' => [
    'depcore\parts\Models\Series',
    'table' => 'depcore_parts_products_series',
    'order' => 'name',
    ],
  'departments' => [
    'depcore\parts\Models\Department',
    'table' => 'depcore_parts_products_departments',
    // 'order' => 'name'
    ]
];

DepartmentSeries模型

public $hasMany = [
  'products' => [
    '\depcore\parts\Models\Product',
    'table' => 'depcore_parts_products_departments',
  ]
];

Color型号

public $hasMany = [
  'products' => [
    '\depcore\Parts\Models\Product'
  ]
];

用户输入通过 ajax 发送到现在看起来像这样的函数

public function onFilterProducts(){

  $filters = Request::input('Filter');

  if ( isset( $filters['colors'] ) or isset( $filters['departments'] ) or isset ( $filters['series'] ) ) {

    // $this->page['products'] = Product::whereIn ( 'color_id', $filters['colors']   )->take( 10 )->get();
    $this->page['products'] = Product::where ( function ( $query ) use  ( $filters ) {

      if ( isset ( $filters['colors'] ) ) $query->whereIn('color_id', $filters['colors']);
      if ( isset ( $filters['series'] ) ) $query->with(
        ['series'=> function ( $subquery ) {
          $subquery->whereIn('series_id', $filters['series']);
      }]);

    }  )->take(9)->get();

  }
  else
    $this->page['products'] =  Product::listFrontEnd();

}

如您所见,我正在尝试在颜色查询之后对与系列模型的多对多关系进行过滤(这个工作正常)。

问题出在多对多关系上,我尝试使用不同的方法来解决这个问题,要么没有错误(但也没有结果),要么有一个错误说下面的函数where不起作用。

if ( isset ( $filters['series'] ) ) $query->series()->whereIn ( 'series', $filters['series'] );

/var/www/public/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php 的第 1421 行“调用未定义的方法 depcore\parts\Models\Product::where()”

我不知道这是否有可能以这种方式实现,还是我需要采取不同的方法?

4

1 回答 1

0

所以这是我想出的解决方案,使用 thenwhereIn方法创建另一个匿名函数

if ( isset ( $filters['series'] ) ) {
   $query->whereHas ( 'series', function ( $q ) use  ( $filters ){ 
        $q->whereIn ( 'id', $filters['series'] ); } 
 );
  }
于 2017-10-26T09:22:56.910 回答