相關模型首先,我知道這裏有一個類似的問題:Filter setup for related model in GridView。我試圖遵循這一點,但這並沒有成功。搜索+ GridView(yii2)
我也檢查了不同的指南如何去,但我仍然堅持。 作爲參考,我在這裏
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,我得到的名稱(這是我想要的東西)。但由於某些原因,這些字段不可排序也不可搜索。
表「製造商」 以及表「供應商」有一欄「名」
感謝在正確的方向上沒有任何提示。