<p>If you want to add a default to an existing column in a table in a migration, you'd do something like this:</p>

<pre><code>$this-&gt;alterColumn('tableName', 'columnName', array('column' =&gt; ColumnType::Number, 'default' =&gt; 0));
</code></pre>

<p>If you want to add a default to a new column in a table in a migration, you'd do something like this:</p>

<pre><code>$this-&gt;addColumn('tableName', 'columnName', array('column' =&gt; ColumnType::Number, 'default' =&gt; 0));
</code></pre>

CC BY-SA 3.0
2016-04-08T03:12:55.927Z
2016-04-08T03:12:55.927Z
Brad Bell
<p>I've got a default value defined in my model for a field</p>

<pre><code>'limit' =&gt; array(AttributeType::Number, 'default' =&gt; 0)
</code></pre>

<p>When I create a new record, if the limit field is empty, <code>NULL</code> gets stored in the DB instead of 0. I thought <code>$model->setAttributes()</code> would set the default values if the values coming in were <code>NULL</code>. What am I missing?</p>

CC BY-SA 3.0
2016-04-03T12:30:00.537Z
Did you define the default value for the attribute in your record as well?
Steve Rowling
CC BY-SA 3.0
2016-04-03T14:10:26.543Z
Yes, it's on the record as well.
Trevor Davis
CC BY-SA 3.0
2016-04-03T22:08:19.490Z
Does the `limit` column in the database have a default set?  Did the record create the table?
Brad Bell
CC BY-SA 3.0
2016-04-04T13:36:51.693Z
Ahhh nope because this column was added in a DB migration. How can I set the default value in a migration?
Trevor Davis
<plugin-development><models><records>
Plugin Use Default Value When Empty
# Plugin Use Default Value When Empty

(Asked by: username_0 on 2016-04-02)

I've got a default value defined in my model for a field
'limit' => array(AttributeType::Number, 'default' => 0)

When I create a new record, if the limit field is empty, NULL gets stored in the DB instead of 0. I thought $model->setAttributes() would set the default values if the values coming in were NULL. What am I missing?

**Tags:** plugin-development, models, records

> **Comments:**
> **username_1**: Did you define the default value for the attribute in your record as well?  
> **username_0**: Yes, it's on the record as well.  
> **username_2**: Does the `limit` column in the database have a default set?  Did the record create the table?  
> **username_0**: Ahhh nope because this column was added in a DB migration. How can I set the default value in a migration?  

---

## 1 answers

### Answer by username_2 on 2016-04-08. Score: 0 | Accepted answer

If you want to add a default to an existing column in a table in a migration, you'd do something like this:
$this->alterColumn('tableName', 'columnName', array('column' => ColumnType::Number, 'default' => 0));

If you want to add a default to a new column in a table in a migration, you'd do something like this:
$this->addColumn('tableName', 'columnName', array('column' => ColumnType::Number, 'default' => 0));


---

