<p>I had a similar problem, ended up using multiple setAttribute() calls instead of setAttributes().</p>

<p>I created an array of attributes separately and then looped through them and called setAttribute for each one, seemed to do the trick.</p>

<pre><code>if ($id = $model-&gt;getAttribute('id')) {
    if (null === ($record = $this-&gt;myRecord-&gt;findByPk($id))) {
            throw new Exception(Craft::t('Can\'t find item with ID "{id}"', array('id' =&gt; $id)));
        }
    } else {
        $record = $this-&gt;myRecord-&gt;create();
    }

    /* Not this: */       
    $record-&gt;setAttributes($model-&gt;getAttributes());

    /* This instead: */
    $attributes = array(
        'column1' =&gt; $col1,
        'column2' =&gt; $col2
    );    
    foreach($attributes as $k =&gt; $v) $record-&gt;setAttribute($k,$v);
}
</code></pre>

CC BY-SA 3.0
2015-04-08T13:33:18.140Z
I also had this exact problem once. I used the above solution to get me rolling, but help from others to finally resolve it. [Check out my thread](http://craftcms.stackexchange.com/questions/8884/save-contact-form-data-to-database/8895#8895) to see what was causing the problem. TL;DR: validation is causing it.
Damon
CC BY-SA 3.0
2015-01-25T21:23:21.460Z
2015-01-25T21:23:21.460Z
Matt Nicholson
<p>I'm having trouble saving some data into the database with my plugin. I am able to save content only if an index is defined on that column, but only if unique=>true is set, which causes some problems because I need repeated values in column b. My function that runs after plugin install works, as I am able to save all the correct content in column A. Data is saved in column b if I set a unique index on it, otherwise the column fills with Null. Any help is greatly appreciated! </p>

<p>Model:</p>

<pre><code>namespace Craft;

class Plugin_MyModel extends BaseModel
{
    public $a = "";
    public $b = "";

    protected function defineAttributes()
    {
        return array(
            'a' =&gt; AttributeType::String,
            'b' =&gt; AttributeType::String,
        );
    }
}
</code></pre>

<p>Record:</p>

<pre><code>&lt;?php

namespace Craft;

class Plugin_MyRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'my_table';
    }

    protected function defineAttributes()
    {
        return array(
            'a'     =&gt; AttributeType::String,
            'b' =&gt; AttributeType::String,
        );
    }

    public function defineIndexes()
    {
        return array(
            array('columns' =&gt; array('a'), 'unique' =&gt; true),
        );
    }
}
</code></pre>

<p>Service that gets data from API call and attempts to save in DB:</p>

<pre><code>&lt;?php

namespace Craft;

class Plugin_MyService extends BaseApplicationComponent
{

    protected $myRecord;

    public function __construct($myRecord = null)
    {
        $this-&gt;myRecord = $myRecord;
        if(is_null($this-&gt;myRecord))
        {
            $this-&gt;myRecord = Plugin_MyRecord::model();
        }   
    }


    public function saveItem(Plugin_MyModel &amp;$model)
    {
        if ($id = $model-&gt;getAttribute('id')) {
            if (null === ($record = $this-&gt;myRecord-&gt;findByPk($id))) {
                throw new Exception(Craft::t('Can\'t find item with ID "{id}"', array('id' =&gt; $id)));
            }
        } else {
            $record = $this-&gt;myRecord-&gt;create();
        }

        $record-&gt;setAttributes($model-&gt;getAttributes());
        if ($record-&gt;save()) {
            // update id on model (for new records)
            $model-&gt;setAttribute('id', $record-&gt;getAttribute('id'));

            return true;
        } else {
            $model-&gt;addErrors($record-&gt;getErrors());

            return false;
        }
    }


    public function loadAllItems()
    {
        $items = $this-&gt;api();

        foreach($items['Items'] AS $item)
        {        
            $new_item = new Plugin_MyModel();
            $new_item-&gt;a = $item['a'];
            $new_item-&gt;b = $item['b'];
            $this-&gt;saveItem($new_item);
        }
    }

    private function api(){
        //Returns API Data  
    }
}
</code></pre>

CC BY-SA 3.0
2014-09-28T01:22:30.480Z
1) Can you post the code you're using to save to the database and 2) What's the point of the public $a and $b properties on the model?
Brad Bell
CC BY-SA 3.0
2014-09-28T12:17:50.277Z
When you’re making changes to your record, are you also updating the DB table? The only time Craft will automatically make DB schema changes for you is right when you install a plugin.
Brandon Kelly
CC BY-SA 3.0
2014-09-28T16:08:03.540Z
Just added the Service class that gets data from an API call and attempts to save it into the DB. Thanks for taking a look!
Aaron Berkowitz
CC BY-SA 3.0
2014-09-28T20:33:29.063Z
Awesome.  Can you add that as the official answer?
Brad Bell
CC BY-SA 3.0
2014-09-28T22:05:39.660Z
Sorry, just saying that I put the Service class in the code above for review. Still not working properly.
Aaron Berkowitz
<plugin-development><database>
Plugin only saving one column in database
# Plugin only saving one column in database

(Asked by: username_0 on 2014-09-27)

I'm having trouble saving some data into the database with my plugin. I am able to save content only if an index is defined on that column, but only if unique=>true is set, which causes some problems because I need repeated values in column b. My function that runs after plugin install works, as I am able to save all the correct content in column A. Data is saved in column b if I set a unique index on it, otherwise the column fills with Null. Any help is greatly appreciated! 
Model:
namespace Craft;

class Plugin_MyModel extends BaseModel
{
    public $a = "";
    public $b = "";

    protected function defineAttributes()
    {
        return array(
            'a' => AttributeType::String,
            'b' => AttributeType::String,
        );
    }
}

Record:
 AttributeType::String,
            'b' => AttributeType::String,
        );
    }

    public function defineIndexes()
    {
        return array(
            array('columns' => array('a'), 'unique' => true),
        );
    }
}

Service that gets data from API call and attempts to save in DB:
myRecord = $myRecord;
        if(is_null($this->myRecord))
        {
            $this->myRecord = Plugin_MyRecord::model();
        }   
    }


    public function saveItem(Plugin_MyModel &$model)
    {
        if ($id = $model->getAttribute('id')) {
            if (null === ($record = $this->myRecord->findByPk($id))) {
                throw new Exception(Craft::t('Can\'t find item with ID "{id}"', array('id' => $id)));
            }
        } else {
            $record = $this->myRecord->create();
        }

        $record->setAttributes($model->getAttributes());
        if ($record->save()) {
            // update id on model (for new records)
            $model->setAttribute('id', $record->getAttribute('id'));

            return true;
        } else {
            $model->addErrors($record->getErrors());

            return false;
        }
    }


    public function loadAllItems()
    {
        $items = $this->api();

        foreach($items['Items'] AS $item)
        {        
            $new_item = new Plugin_MyModel();
            $new_item->a = $item['a'];
            $new_item->b = $item['b'];
            $this->saveItem($new_item);
        }
    }

    private function api(){
        //Returns API Data  
    }
}

**Tags:** plugin-development, database
> **Comments:**
> **username_1**: 1) Can you post the code you're using to save to the database and 2) What's the point of the public $a and $b properties on the model?  
> **username_2**: When you’re making changes to your record, are you also updating the DB table? The only time Craft will automatically make DB schema changes for you is right when you install a plugin.  
> **username_0**: Just added the Service class that gets data from an API call and attempts to save it into the DB. Thanks for taking a look!  
> **username_1**: Awesome.  Can you add that as the official answer?  
> **username_0**: Sorry, just saying that I put the Service class in the code above for review. Still not working properly.  

---

## 1 answers

### Answer by username_3 on 2015-01-25. Score: 2

I had a similar problem, ended up using multiple setAttribute() calls instead of setAttributes().
I created an array of attributes separately and then looped through them and called setAttribute for each one, seemed to do the trick.
if ($id = $model->getAttribute('id')) {
    if (null === ($record = $this->myRecord->findByPk($id))) {
            throw new Exception(Craft::t('Can\'t find item with ID "{id}"', array('id' => $id)));
        }
    } else {
        $record = $this->myRecord->create();
    }

    /* Not this: */       
    $record->setAttributes($model->getAttributes());

    /* This instead: */
    $attributes = array(
        'column1' => $col1,
        'column2' => $col2
    );    
    foreach($attributes as $k => $v) $record->setAttribute($k,$v);
}

> **Comments:**
> **username_4**: I also had this exact problem once. I used the above solution to get me rolling, but help from others to finally resolve it. [Check out my thread](http://craftcms.stackexchange.com/questions/8884/save-contact-form-data-to-database/8895#8895) to see what was causing the problem. TL;DR: validation is causing it.  

---

