本文介绍了如何在 Yii2 gridview 中连接两个表并获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Yii2 gridview widget 来显示数据.
I'm using Yii2 gridview widget to display the data.
我使用了两个名为 message 和 message_trigger 的表.
I'm using two tables named as message and message_trigger.
在message 表中的列是object_model
、Object_id
.
在message_trigger中的列是object_id
,object_name
.
网格从表格消息中获取值.所以网格字段是Object_model
、Object_id
.
The grid get the values from the table message. So grid fields are Object_model
, Object_id
.
现在我的问题是我需要根据表 message 中的 object_id
显示表 message_trigger
中的 Object_name
强>.
Now my problem is I need to show Object_name
from the table message_trigger
based on the object_id
from the table message.
在我的表单中,我使用了这样的网格
In my form I have used grid like this
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yiigridSerialColumn'],
'object_model',
'object_id',
['class' => 'yiigridActionColumn', 'template' => '{view} {update} {delete} '],
],
]); ?>
在我使用过的模型中
public function search($params){
$query = AlertTrigger::find()->where(['alert_id'=>$params['id']])->andWhere(['!=','status',2]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
}
推荐答案
In Message
Model
public function getMessageTrigger()
{
return $this->hasOne(MessageTrigger::className(), ['object_id' => 'object_id']);
}
在视图中
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yiigridSerialColumn'],
'object_model',
'object_id',
[
'label' => 'Name',
'value' => 'messageTrigger.object_name',
],
['class' => 'yiigridActionColumn', 'template' => '{view} {update} {delete} '],
],
]); ?>
这篇关于如何在 Yii2 gridview 中连接两个表并获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!