我尝试在Yii2的GridView小部件中设置相关模型的过滤器,但我一直得到错误,比如过滤器值必须是整数。
我已经关注了this question。现在,我有一个两个型号的Services.php
和ServiceCharge.php
。
在ServiceCharge.php
中,关系设置如下:
public function getServiceName()
{
return $this->hasOne(Services::className(),['id'=>'service_name']);
}
在ServiceChargeSearch.php
中的代码是这样的:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ServiceCharges;
/**
* ServiceChargesSearch represents the model behind the search form about `app\models\ServiceCharges`.
*/
class ServiceChargesSearch extends ServiceCharges
{
/**
* @inheritdoc
*/
public function attributes()
{
// add related fields to searchable attributes
return array_merge(parent::attributes(), ['serviceName.services']);
}
public function rules()
{
return [
[['id'], 'integer'],
[['charges_cash', 'charges_cashless'], 'number'],
[['id', 'serviceName.services', 'room_category'], '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 = ServiceCharges::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['serviceName.services'] = [
'asc' => ['serviceName.services' => SORT_ASC],
'desc' => ['serviceName.services' => SORT_DESC],
];
$query->joinWith(['serviceName']);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
// 'service_name' => $this->service_name,
'room_category' => $this->room_category,
'charges_cash' => $this->charges_cash,
'charges_cashless' => $this->charges_cashless,
])
->andFilterWhere(['LIKE', 'serviceName.services', $this->getAttribute('serviceName.services')]);
return $dataProvider;
}
}
在我Gridview中,它是这样设置的:
[
'attribute'=>'service_name',
'value'=>'serviceName.services',
],
它正确地显示了相关模型中的服务名称。
我看不出我做错了什么,但是服务属性的筛选字段根本没有显示。
2条答案
按热度按时间yhqotfr81#
实际上它比看起来要简单得多。
1.将
column_name
添加到安全属性。注意:这应该是关系名称1.使用类似于-
$query->joinWith(['serviceName','roomCategory']);
的查询添加连接1.添加如下筛选条件:
1.如果要添加排序,请添加如下代码:
5您还应该设置关系名称,例如
public $roomCategory
对相关表的排序和筛选都能很好地工作。
注意:请删除默认验证,如相关列的整数和
gii
生成的默认筛选,否则将生成错误。更新最新版本:
这只是个例子
请记住,你使用的是
relation_name.related_table_attribute_name
过滤器不知何故不为我工作.vfwfrxfs2#
on the Yii Framework website有一套相当全面的指令集。唯一需要注意的是搜索模型会抱怨以下几行,但没有它们,一切似乎都能按预期工作:
对于模型,PaymentEvent(表:subs_payment_event),它有一个链接到模型Currency的currency_id字段,这是完整的附加代码集(使用Basic模板):
在主模型PaymentEvent.php中:
在搜索模型PaymentEventSearch.php中:
在其规则中:
在其setSort语句的属性中,包括:
前电网滤波条件:
最后,在GridView视图中的columns数组(包括我通常跨到相关模型的链接记录):