当我使用 hasMany-> viaTable 关系时,如何过滤(搜索)gridView?
我有3个表 - 产品,组件,componentsMap (表格填充正确)
产品通过 componentsMap 表 - 结构:
与组件连接id | component_id | product_id
我正在使用此方法进行连接:
public function getComponents()
{
return $this->hasMany(Components::className(),
['id' => 'component_id'])
->viaTable('componentsMap', ['product_id' => 'id']);
}
搜索功能:
public function search($params)
{
$query = Products::find();
$this->load($params);
$query->select(
'products.*,
tradeNames.name AS tradeName,
components.name AS componentName, components.no_cas AS cas, components.no_einecs AS einecs')
->from('products')
->with(['components', 'tradeName'])
->leftJoin('componentsMap', 'componentsMap.product_id = products.id')
->leftJoin('components', 'componentsMap.component_id = components.id')
->leftJoin('tradeNamesMap', 'tradeNamesMap.product_id = products.id')
->leftJoin('tradeNames', 'tradeNamesMap.tradeName_id = tradeNames.id')
->andFilterWhere(['LIKE', 'LOWER(inci)', strtolower($this->inci)])
->andFilterWhere(['LIKE', 'LOWER(tradeNames.name)', strtolower($this->tradeName)])
->andFilterWhere(['LIKE', 'LOWER(chemical_name)', strtolower($this->chemical_name)])
->andFilterWhere(['LIKE', 'created_at', $this->created_at]);
return new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'inci' => SORT_ASC,
]
],
]);
}
在gridView中我使用此代码来显示组件:
[
'attribute' => 'componentName',
'format' => 'raw',
'label' => 'Components',
'value' => function($model){
$components = $model->components;
$i = 1;
$content = "";
foreach($components as $component):
$content .= '<div class=product-component>';
$content .= "<h3>Component {$i}</h3>";
$content .= '<strong>Name:</strong> ' . $component->name . '<br>';
$content .= '<strong>CAS:</strong> ' . $component->no_cas . '<br>';
$content .= '<strong>EINECS:</strong> ' . $component->no_einecs . '<br>';
$content .= '</div>';
$i++;
endforeach;
return $content;
}
],