Laravel Violates not-null constraint with default value - sql

I am having an issue with Laravel and default values. I created the field in my table like so:
$table->string('title', 255)->default('');
And in the model, I have a default set again using this:
protected $attributes = [
'title' => '',
];
Yet I am always getting this error:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column
"title" violates not-null constraint DETAIL: Failing row contains
(3dd07c7a-e3f3-4f20-8d16-0f066b219dc2, dsfs, sdfs, null, null, null,
sdfs, null, 0, 0, 0, 0, 0, 0, null, null, null). (SQL: insert into
"users" ("title", "first_name", "last_name", "email", "business_unit",
"linkedin_profile") values (, dsfs, sdfs, sdfs, , ) returning
"user_id")
My abbreviated save action (example without validation) is the following:
$data = Input::all();
$user = new Users($data);
$user->save();
The following is the $data:
array (size=12)
'_token' => string '0EI9JGmgiNDAqmv83pdQZaktyWNLiX3GB9JQSfvA' (length=40)
'first_name' => string 'ads' (length=3)
'last_name' => string 'asd' (length=3)
'email' => string 'asd' (length=3)
'title' => null
'business_unit' => null
'linkedin_profile' => null
'is_admin' => string '0' (length=1)
'is_employee' => string '0' (length=1)
'is_manager' => string '0' (length=1)
'is_trainer' => string '0' (length=1)
'rt' => string '/users' (length=6)
How come my default value is not being set?

The problem is that your database column does not allow null values for title.
You can allow them like this:
$table->string('title')->nullable()->default('');
Or even without the default to have it as NULL by default:
$table->string('title')->nullable();
Otherwise, you have to make sure your title is not null.
If you don't want to allow null values and convert it automatically to empty string, you can add a mutator like this to your model:
public function setTitleAttribute($title)
{
$this->attributes['title'] = is_null($title) ? '' : $title;
}
For more information: https://laravel.com/docs/5.6/eloquent-mutators

Because the 'title' key is in the provided array, it'll try to insert it: you should be able to insert null values.
You could use a mutator setTitleAttribute($val) method in your Model class, or simply unset the 'title' array key if the value is empty before inserting. You could also filter using collection helpers or array_filter to remove unset all null values.

Related

TYPO3 error: Incorrect integer value: '' for column at row 1

I'm using TYPO3. I programmed an extension called 'Eventmanager', to manage events.
After installing this extension, in Backend I can add/edit event-records. With each record there is a field called end_time, which is a datetime-picker, for choosing the date and time of the events.
Today I edit an event-record. I deleted the value of this end_time field (to make it empty), and tried to save this record. But an error occurred during saving:
2: SQL error: 'Incorrect integer value: '' for column 'event_end_time' at row 1' (tx_eventmanager_domain_model_event:13)
The Settings in TCA is shown as follows:
'endtime' => array(
'exclude' => 1,
'l10n_mode' => 'mergeIfNotBlank',
'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.endtime',
'config' => array(
'type' => 'input',
'size' => 13,
'max' => 20,
'eval' => 'datetime',
'checkbox' => 0,
'default' => 0,
'range' => array(
'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y'))
),
),
),
and the definition in the file 'ext_tables.sql' is shown as follows:
event_end_time int(11) DEFAULT '0' NOT NULL
Can someone tell my what is the reason? How can I solve this problem?

if in array when value null

I have a sql command like the following:
DB::table('tb_angsuran_lainlain')->insert(array(
array('id_kegiatan'=>'1','id_siswa'=>'26338','id_bulan'=>'1','nominal'=>'300000'),
array('id_kegiatan'=>'2','id_siswa'=>'26338','id_bulan'=>'1','nominal'=>'300000'),
array('id_kegiatan'=>'','id_siswa'=>'','id_bulan'=>'','nominal'=>''),
));
I want when the value is empty, it does not fill in the value in the table
array('id_kegiatan'=>'','id_siswa'=>'','id_bulan'=>'','nominal'=>''),
How to master ?
If I understood your question correctly, you only want to create a row for records that has some of their values filled.
To achieve that, use array_filter to get only those record that have some values:
$records = [
['some' => '1', 'key' => '2'],
['some' => '3', 'key' => '4'],
['some' => '', 'key' => ''],
];
$records = array_filter($records, function ($record) {
return count(array_filter($record));
});
DB::table('table_name')->insert($records);

relation definition not for primary index columns

Database structure is
Yii::app()->db->createCommand()->createTable('ar_table_column', array(
'col_int1' => 'integer NULL',
'col_int2' => 'integer NULL',
'col_int3' => 'integer NULL',
'col_id' => 'pk',
));
Yii::app()->db->createCommand()->createTable('ar_table', array(
'table_int1' => 'integer NULL',
'table_int2' => 'integer NULL',
'table_int3' => 'integer NULL',
'table_id' => 'pk',
));
Yii::app()->db->createCommand()->createIndex('ar_table_idx', 'ar_table',
'table_int1', true);
I need such a relation - table can have many columns bound with ar_table_column.col_int2 = ar_table.table_int1 (not primary key, but note that table_int1 is unique). I need this relation from column point of view, i.e. I need to have access to table from each column.
First trial:
'table' => array(self::BELONGS_TO, 'ArTable', '',
'on' => 't.col_int2=table.table_int1', ),
And this is a half-good solution. There are 2 cases. First:
$columnInRelation = ArColumn::model()->with('table')->find();
$tableInRelation = $columnInRelation->table;
var_export($tableInRelation->attributes);
and it works well - I get correct array of attributes.
Second case:
$columnInRelation = ArColumn::model()->find();
$tableInRelation = $columnInRelation->table;
var_export($tableInRelation->attributes);
and there I get a SQL error from query:
SELECT table.table_int1 AS t1_c0, table.table_int2 AS t1_c1, table.table_int3 AS t1_c2, table.table_id AS t1_c3 FROM ar_table table WHERE (t.col_int2=table.table_int1)
Error is obvious.
How should I define relation to have it available in both cases - using with() and not using ?
Relation should be according to http://www.yiiframework.com/doc/guide/1.1/en/database.arr
'table' => array(self::BELONGS_TO, 'ArTable', array('col_int2' => 'table_int1')),

SugarCRM - Add leads with auto-incremented ID

I use the SOAP API to add new leads to SugarCRM. Additionally, I use a plugin to assign an auto-incremented lead ID whenever a new lead is created (http://www.sugarforge.org/projects/autoincrement/).
Now, the plugin works fine, if I create a new lead via frontend. But, if I use the SOAP API, the function from the module, which assigns the auto-increment ID to the lead, does not trigger.
I create the lead via
$module = 'Leads';
$params = array(
'session' => $session,
'module_name' => $module,
'name_value_list' => array(
array('name' => 'id', 'value' => ''),
//array('name' => 'int_lead_id_c', 'value' => ''),
array('name' => 'first_name', 'value' => $_POST["first_name"]),
array('name' => 'last_name', 'value' => $_POST["last_name"]),
array('name' => 'phone_home', 'value' => $_POST["phone"]),
array('name' => 'email1', 'value' => $_POST["email"]),
array('name' => 'assigned_user_id', 'value' => '1'),
)
);
//Create the Lead record
$lead_result = $soapclient->call('set_entry', $params);
The function in the module is this one:
class SugarFieldAutoincrement extends SugarFieldBase {
/**
* Override the SugarFieldBase::save() function to implement the logic to get the next autoincrement value
* and format the saved value based on the attributes defined for the field.
*
* #param SugarBean bean - the bean performing the save
* #param array params - an array of paramester relevant to the save, most likely will be $_REQUEST
* #param string field - the name of the field
*/
public function save(&$bean, $params, $field, $properties, $prefix = '') {
}
}
How can I make sure, that this function is also triggered, when adding leads via SOAP API?
Thanks a lot for your help! :-)
David
You would need to set the field type to 'autoincrement' and the dbType to 'int' in the vardef record for the field.
If I'm not mistaken, the Database has a UUID() trigger on insert for most tables, so you should be able to completely remove the id field.
If you want to trigger the function before saving, you can use beforeSave logic hook.

Getting specific data from database

I have a table called Category with a few columns and I'm trying to get only a few out of my database.
So I've tried this:
$sql = 'SELECT uppercat AS id, COUNT(uppercat) AS uppercat FROM category GROUP BY uppercat;';
$d = Yii::app()->db->createCommand($sql)->query();
But I find the output strange. I was trying to do an array_shift but I get an error that this isn't an array. When I do a var_dump on $d:
object(CDbDataReader)[38]
private '_statement' =>
object(PDOStatement)[37]
public 'queryString' => string 'SELECT uppercat AS id, COUNT(uppercat) AS uppercat FROM category GROUP BY uppercat;' (length=100)
private '_closed' => boolean false
private '_row' => null
private '_index' => int -1
private '_e' (CComponent) => null
private '_m' (CComponent) => null
Ok.. then I did a foreach on $id:
array
'id' => string '0' (length=1)
'uppercat' => string '6' (length=1)
array
'id' => string '3' (length=1)
'uppercat' => string '2' (length=1)
array
'id' => string '6' (length=1)
'uppercat' => string '1' (length=1)
array
'id' => string '7' (length=1)
'uppercat' => string '2' (length=1)
array
'id' => string '9' (length=1)
'uppercat' => string '2' (length=1)
Then why do I get the message that $id isn't an array while it contains arrays?
Is there any other way on how to get some specific data out of my database and that I can then do an array_shift on them? I've also tried doing this with findAllBySql but then I can't reach my attribute for COUNT(uppercat) which is not in my model. I guess I'd have to add it to my model but I wouldn't like that because I need it just once.
CDbCommand's query returns a CDbDataReader object for fetching the query result. Use queryAll instead, that returns an array of rows.
However, it is nicer if you do it with CDbCriteria (you need a model property for that, you're right).
It would look something like this, assuming the property is called countUppercat.
$criteria = new CDbCriteria;
$criteria->select = 'uppercat, COUNT(uppercat) AS countUppercat';
$criteria->group = 'countUppercat';
$models = CategorieModel::model()->findAll($criteria);
Try this.. its closed which you approched used...
$sql = 'SELECT uppercat AS id, COUNT(uppercat) AS uppercat FROM categorie GROUP BY uppercat;';
$d = Yii::app()->db->createCommand($sql)->queryAll();
and after that when you want to see your array so use,
print_r($d);
so you get the array..
it will work for you..