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:
<?php
namespace Craft;
class Plugin_MyRecord extends BaseRecord
{
public function getTableName()
{
return 'my_table';
}
protected function defineAttributes()
{
return array(
'a' => 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:
<?php
namespace Craft;
class Plugin_MyService extends BaseApplicationComponent
{
protected $myRecord;
public function __construct($myRecord = null)
{
$this->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
}
}