首先,我知道这里有一个类似的问题:Filter setup for related model in 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功能。
My 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']);
}
我的制造商SearchSearch.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,我得到了名字(这是我想要的)。但由于某些原因,这些字段不可排序也不可搜索。
表“制造商”以及表“供应商”有一列“名称”
感谢任何正确方向的提示。
答案 0 :(得分:1)
在ManufactuiresSearch中,您还需要加入过滤器
$query->andFilterWhere(['like', 'name', $this->name]);
$query->joinWith(['vendor' => function ($q) {
$q->andFilterWhere(['like', 'vendor.vendor', $this->vendor]);
}]);
return $dataProvider;