Как объединить две таблицы по внешнему ключу
-
- Сообщения: 6
- Зарегистрирован: 2017.04.19, 08:55
Как объединить две таблицы по внешнему ключу
Есть две таблицы: "sms_connect_menu" и "status_include".
"sms_connect_menu"
id int(100) auto_increment
id_cafe int(100)
textMess varchar(50)
status_menu_SMS int(1)
и
"status_include"
id int(1) auto_increment
statusInc int(1)
label varchar(255)
При помощи Gii генератора создал для них модели, контроллеры и представления, указал связи в моделях по полям "status_menu_SMS" и "statusInc".
Мене нужно чтобы в представлении модели, таблицы "sms_connect_menu", вместо цифры из поля "status_menu_SMS" отображалось слово из поля "label", таблицы "status_include".
Может это глупый вопрос, но для меня затруднителен, как для новичка, может подскажет кто нибудь, решение или статью, где про это написано.
Заранее спасибо!
"sms_connect_menu"
id int(100) auto_increment
id_cafe int(100)
textMess varchar(50)
status_menu_SMS int(1)
и
"status_include"
id int(1) auto_increment
statusInc int(1)
label varchar(255)
При помощи Gii генератора создал для них модели, контроллеры и представления, указал связи в моделях по полям "status_menu_SMS" и "statusInc".
Мене нужно чтобы в представлении модели, таблицы "sms_connect_menu", вместо цифры из поля "status_menu_SMS" отображалось слово из поля "label", таблицы "status_include".
Может это глупый вопрос, но для меня затруднителен, как для новичка, может подскажет кто нибудь, решение или статью, где про это написано.
Заранее спасибо!
Re: Как объединить две таблицы по внешнему ключу
В представлении доступно так: $model->relationNameModel->attribute
Т.е. в вашем случае типа такого $sms_connect_menu->status_menu_SMS->label
Если в GridView используете то можете в колонке указать через точку
'columns' => [ 'relationNameModel.attribute'',...]
http://www.yiiframework.com/doc-2.0/gui ... ional-data
http://www.yiiframework.com/doc-2.0/gui ... -relations
Т.е. в вашем случае типа такого $sms_connect_menu->status_menu_SMS->label
Если в GridView используете то можете в колонке указать через точку
'columns' => [ 'relationNameModel.attribute'',...]
http://www.yiiframework.com/doc-2.0/gui ... ional-data
http://www.yiiframework.com/doc-2.0/gui ... -relations
Re: Как объединить две таблицы по внешнему ключу
int(100) о_О
-
- Сообщения: 6
- Зарегистрирован: 2017.04.19, 08:55
Re: Как объединить две таблицы по внешнему ключу
Что-то не так, может потому что я использую yii 1.x
Указываю, поле "label" из связанной таблицы, заголовок отображается правильно, ошибок нет а значения пустые
Указываю, поле "label" из связанной таблицы, заголовок отображается правильно, ошибок нет а значения пустые
-
- Сообщения: 6
- Зарегистрирован: 2017.04.19, 08:55
Re: Как объединить две таблицы по внешнему ключу
В этом плане yii1 и yii2 одинаковые, может select не все поля подтягивает....
-
- Сообщения: 6
- Зарегистрирован: 2017.04.19, 08:55
Re: Как объединить две таблицы по внешнему ключу
Модель таблицы "sms_connect_menu"
Представление
Модель таблицы "status_include" не менялась, т.е. осталась такой, как создал её gii генератор, я только указал связь
Код: Выделить всё
class SmsConnectMenu extends CActiveRecord
{
public $label = null;
public $statusInc = null;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'sms_connect_menu';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('id_cafe, textMess, status_menu_SMS', 'required'),
array('id_cafe, status_menu_SMS', 'numerical', 'integerOnly'=>true),
array('textMess', 'length', 'max'=>50),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('statusInc, label, id, id_cafe, textMess, status_menu_SMS', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'relationsSmsConnectMenuStatusInclude'=>array(self::HAS_MANY, 'StatusInclude', 'statusInc'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'id_cafe' => 'ID кафе',
'textMess' => 'Текст сообщения',
'status_menu_SMS' => 'Статус отображения меню',
'label' => 'Статус подключения меню',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->with=array(
'relationsSmsConnectMenuStatusInclude',
);
$criteria->compare('id',$this->id);
$criteria->compare('id_cafe',$this->id_cafe);
$criteria->compare('textMess',$this->textMess,true);
$criteria->compare('status_menu_SMS',$this->status_menu_SMS);
$criteria->compare('relationsSmsConnectMenuStatusInclude.label',$this->label, true);
$criteria->compare('relationsSmsConnectMenuStatusInclude.statusInc',$this->statusInc, true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort' => array(
'defaultOrder' => 'id asc',
'attributes'=>array(
'id',
'id_cafe',
'textMess',
'label' => array(
'asc' => 'relationsSmsConnectMenuStatusInclude.label',
'desc' => 'relationsSmsConnectMenuStatusInclude.label desc',
),
),
),
'pagination' => array(
'pageSize' => 25,
),
));
}
/**
* @return CDbConnection the database connection used for this class
*/
public function getDbConnection()
{
return Yii::app()->klient;
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return SmsConnectMenu the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Код: Выделить всё
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'sms-connect-menu-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array('name'=>'id_cafe',),
array('name'=>'textMess',),
array(
'name'=>'label',
'value' => '$data["relationsSmsConnectMenuStatusInclude"]["label"]',
),
array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}{delete}',
),
),
));
Код: Выделить всё
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'relationsStatusIncludeSmsConnectMenu'=>array(self::HAS_MANY, 'SmsConnectMenu', 'status_menu_SMS'),
);
}
-
- Сообщения: 6
- Зарегистрирован: 2017.04.19, 08:55
Re: Как объединить две таблицы по внешнему ключу
У вас же там связь HAS_MANY
т.е. вот это $data["relationsSmsConnectMenuStatusInclude"] должно вернуть массив моделей status_include, а не одну модель!
т.е. вот это $data["relationsSmsConnectMenuStatusInclude"] должно вернуть массив моделей status_include, а не одну модель!
-
- Сообщения: 6
- Зарегистрирован: 2017.04.19, 08:55
Re: Как объединить две таблицы по внешнему ключу
разобрался, благодарю за помощь