Kapil Sharma Kapil Sharma - 2 months ago 7
MySQL Question

cakephp create new field if not present in a table

I do google but not found any proper solution to create a new field if not field.

For example : if I have to add a field according to the title which is in any other language.

title
,
title_eng
,
title_fr
... etc

I found solution in
php
but looking for a solution which is in
cakephp


$languageData = $this->LanguageSetting->find('first', array('conditions' => array('id' => $post['language_id'])));

$short_name = $languageData['LanguageSetting']['short_name'];
$subjectfieldName = "email_subject_" . $short_name;
$contentfieldName = "email_template_" . $short_name;

//add subject field if not present
$subjectfield = $this->LanguageSetting->query("SELECT $subjectfieldName FROM email_managers");
if (!$subjectfield) {
$insert_col = "ALTER TABLE email_managers ADD " . $subjectfieldName . " VARCHAR(255) NULL";
}

//add template field if not present
$contentfield = $this->LanguageSetting->query("SELECT $contentfieldName FROM email_managers");
if (!$contentfield) {
$insert_col = "ALTER TABLE email_managers ADD " . $contentfieldName . " TEXT NULL";
}


I tried above solution but getting this error.


Database Error

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'email_subject_' in 'field list'

Answer

This might help you.

$columns = $this->LanguageSetting->query('show columns from email_managers');
                $exists = FALSE;
                foreach ($columns as $fields) {
                    if ($fields['COLUMNS']['Field'] == $subjectfieldName) {
                        $exists = true;
                        break;
                    }
                }
                if (!$exists) {
                    $this->LanguageSetting->query("ALTER TABLE email_managers ADD " . $subjectfieldName . " VARCHAR(255) NULL");
                }
Comments