This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Hi I'm trying to make an combined query with October CMS active record implementation to filter out user selected input.
The are four models a Color, Series, Department and Product with the relationships as follows:
The Product model
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'
]
];
Department and Series model
public $hasMany = [
'products' => [
'\depcore\parts\Models\Product',
'table' => 'depcore_parts_products_departments',
]
];
And Color model
public $hasMany = [
'products' => [
'\depcore\Parts\Models\Product'
]
];
The user input is sent via ajax to the function which looks like this right now
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();
}
As you can see I'm trying to make a filter on the many-to-many relation with the series model after the color query (this one works OK).
The problem is with the many-to-many relation I've tried to use different approaches to this problem with either no error ( but also no result ) or with an error saying that the below function where does not work.
if ( isset ( $filters['series'] ) ) $query->series()->whereIn ( 'series', $filters['series'] );
"Call to undefined method depcore\parts\Models\Product::where()" on line 1421 of /var/www/public/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
I don't know if this is possible to achieve this way or do I need to make a different approach?
I've asked the same question here https://stackoverflow.com/questions/46928836/query-multiple-relationships-in-model-october-cms
This is how I got it to work, using a second level anonymous function and the whereIn
method
if ( isset ( $filters['series'] ) ) {
$query->whereHas ( 'series', function ( $q ) use ( $filters ){ $q->whereIn ( 'id', $filters['series'] ); } );
}
1-2 of 2