【问题标题】:Query multiple relationships in model october cms查询模型october cms中的多个关系
【发布时间】:2017-10-25 09:31:59
【问题描述】:

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

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'] );

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

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

【问题讨论】:

    标签: octobercms octobercms-plugins illuminate-container


    【解决方案1】:

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

    if ( isset ( $filters['series'] ) ) {
       $query->whereHas ( 'series', function ( $q ) use  ( $filters ){ 
            $q->whereIn ( 'id', $filters['series'] ); } 
     );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 2021-08-27
      • 2021-08-08
      • 2021-05-02
      • 1970-01-01
      • 2017-08-12
      • 2014-01-18
      相关资源
      最近更新 更多