[英]Search + Sort in related model in GridView (yii2)
首先,我知道这里有一个类似的问题: GridView中相关模型的过滤器设置 。 我试图遵循这一点,但这并不能解决问题。
我还查看了有关如何使用的其他指南,但仍然遇到困难。 作为参考,我在这里遵循了这些指南
http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working-with-model-relations
http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/
但是,我仍然没有搜索字段+排序功能。
我使用gii创建了CRUD功能。
我的Manufacturers.php(模型):
// basic model, nothing special here.
// The following line was added to create a relation
public function getVendor()
{
return $this->hasOne(Vendors::className(), ['vendor_id' => 'vendor_id']);
}
我的ManufacturersSearch.php(模型):
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Manufacturers;
/**
* ManufacturersSearch represents the model behind the search form about `app\models\Manufacturers`.
*/
class ManufacturersSearch extends Manufacturers
{
public $vendor;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['manufacturer_id', 'vendor_id'], 'integer'],
[['name', 'vendor'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Manufacturers::find();
$query->joinWith("vendor");
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['vendor_name'] = [
// The tables are the ones our relation are configured to
// in my case they are prefixed with "tbl_"
'asc' => ['vendor.name' => SORT_ASC],
'desc' => ['vendor.name' => SORT_DESC],
];
if (!$this->load($params) && $this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'manufacturer_id' => $this->manufacturer_id,
'vendor_id' => $this->vendor_id,
]);
$query->andFilterWhere(['like', 'name', $this->name]);
$query->andFilterWhere(['like', 'vendor.vendor', $this->vendor]);
return $dataProvider;
}
}
最后是我的查看文件:
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
[
'label' => 'Hauptlieferant',
'value' => 'vendor.name',
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?></div>
这是我当前的输出:
所以,这有点用,因为我得到的是名称(而不是ID),而不是ID。 但是由于某些原因,这些字段无法排序或搜索。
表“ manufacturers” 以及表“ vendors”都有一列“ name ”
感谢您向正确方向提供的任何提示。
在ManufactuiresSearch中,您还需要在过滤器中加入joinWith
$query->andFilterWhere(['like', 'name', $this->name]);
$query->joinWith(['vendor' => function ($q) {
$q->andFilterWhere(['like', 'vendor.vendor', $this->vendor]);
}]);
return $dataProvider;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.