我有一张表 bus_route 它有以下规则
public function rules()
{
return [
[['schedule_id', 'stop_id'], 'required'],
[['schedule_id', 'stop_id', 'route_order', 'is_destination'], 'integer'],
[['departure_time'], 'safe']
];
}
stop_id
(外键)是表停止的主键(id)。
现在,我想在stop_name
表中显示总线路径视图中相应stops
的{{1}}。为此,我在模型
stop_id
并在视图
中'stop.stop_name',
它的工作但搜索功能不适用于停止名称字段。其他字段显示一个框,用于搜索public function getStop()
{
return $this->hasOne(Stop::className(), ['id' => 'stop_id']);
}
字段未显示要搜索的框的位置。我该如何搜索这个字段?
修改
BusrouteSearch.php
stop_id
答案 0 :(得分:1)
参考here
在模型Busroute.php
// ...
class Bus extends \yii\db\ActiveRecord
{
// ...
public function getStop()
{
return $this->hasOne(Stop::className(), ['id' => 'stop_id']);
}
public function getStop_name()
{
if(isset($this->stop->stop_name))
return $this->stop->stop_name;
else
return '(stop name not set)';
}
// ...
}
// ...
在搜索模型BusrouteSearch.php
class BusrouteSearch extends Busroute
{
// ...
public $stop_name;
public function rules()
{
return [
// other attributes
[['stop_name'], 'safe'],
];
}
public function search($params)
{
$query = BusRoute::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes' => [
'id',
// other attribute
'stop_name' => [
'asc' => ['stops.stop_name' => SORT_ASC],
'desc' => ['stops.stop_name' => SORT_DESC],
'label' => 'Stop name',
'default' => SORT_ASC
],
// other attribute
]
]);
$query->joinWith(['stop']);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'schedule_id' => $this->schedule_id,
'departure_time' => $this->departure_time,
'route_order' => $this->route_order,
'is_destination' => $this->is_destination,
]);
$query->andFilterWhere(['like', 'stops.stop_name', $this->stop_name]);
return $dataProvider;
}
// ...
}
在视图文件index.php
中(可能是@app/views/bus/index.php
)
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
// other attributes
'stop_name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>