I'm using Doctrine for database abstraction. Now I'd like to get the auto_increment primary key from the freshly-created (and save()'d) object - but $obj->toArray() shows me that the field is empty after calling save().
Is there a flag that I'm not aware of that does this? Or do I really have to query the object from the database?
Ensure that you have the autoincrement flag set when setting up your object in the setTableDefinition() method (or related YAML config file). If this flag isn't set, then Doctrine won't know to update it. You should have something that looks like this:
$this->hasColumn('id', 'integer', 4, array(
'type' => 'integer',
'length' => 4,
'fixed' => false,
'unsigned' => true,
'primary' => true,
'autoincrement' => true //this flag right here
)
);
Call refresh on the record instance before the toArray.
Related
I tried to set as only biginter but it lost its autoincrement properties. So I tried adding auto-increment as well.
$table->changeColumn('id', 'biginteger', ['identity' => true])->update();
But it showed error.
PDOException: SQLSTATE[42704]: Undefined object: 7 ERROR: type "bigserial" does not exist
How is this possible for PostgreSQL?
For MySQL this works in phinx 0.12
$table = $this->table('mytable', ['id' => false, 'primary_key' => 'id']);
$table->addColumn('id', 'biginteger', ['identity' => true, 'signed' => false])->create();
$permission = new Permission();
$permPost = $permission->create([
'name' => 'post',
'slug' => [ // pass an array of permissions.
'create' => true,
'view' => true,
'update' => true,
'delete' => true
],
'description' => 'manage post permissions'
]);
throwing error on passing array within array on create method laravel 5.4 :
Array to string conversion (SQL: insert into permissions (name, slug, description, updated_at, created_at) values (post, 1, manage post permissions, 2017-04-27 05:32:41, 2017-04-27 05:32:41))
Laravel allows Array & JSON Casting mutator:
Just update your Permission model to have:
protected $casts = [
'slug' => 'array',
];
From the docs:
Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage
So, now you no need to encode manually, Laravel does everything for you automatically! Just pass array as an array.
Try json_encode on slug field, then pass it to the Eloquent to persist in DB:
'slug' => json_encode([
'create' => true,
'view' => true,
'update' => true,
'delete' => true
)]
Slug is a string in the database. You passing an array to it.
You could store it as JSON or Serialise it, but this is a database design smell. You should think about what other tables you need to store this data properly, depending on how it will be used elsewhere in you application.
I have created a yii2 (v2.0.6) migration for a simple MySQL (v5.6.21) table. Everything works, except that I cannot figure out how to AUTO_INCREMENT the primary key. The problem seems to be that I am using a small integer rather than the more standard long integer datatype. Here is my migration code:
$this->createTable('{{%status}}', [
'id' => $this->smallInteger(8)->unique(),
//'id' => $this->primaryKey(11),
'description' => $this->string(20),
]);
$this->addPrimaryKey('','status','id');
I could get around the problem by using the ->primaryKey() method, which is commented out in line 3 above, but then yii creates a long integer datatype, and I am trying to avoid that. Any insight into the problem will be much appreciated.
If it is critical to have that column type, you can always change it:
$this->createTable('{{%status}}', [
'id' => $this->primaryKey(11),
'description' => $this->string(20),
]);
$this->alterColumn('{{%status}}', 'id', $this->smallInteger(8).' NOT NULL AUTO_INCREMENT');
(I've tested this with MySQL - it works)
However, like #scaisEdge says, it's usually not worth the troble.
Why not a simply primaryKey?, the format for integer(8) , integer(11) or primary key is always the same is always an integer long
then or you need a small int (max 5 digit) or you can use the normal $this->primaryKey() because
SMALLINT is for storage of 2 byte (value -32768 32767) an then
smallInteger(8) is not coherent. the numer 8 is for output not for store format. If you want 8 digit you need at least
INT of 4 byte -2147483648 2147483647 or more
$this->createTable('posts', [
'post_id' => "bigint(20) unsigned NOT NULL AUTO_INCREMENT",
'loc_id' => $this->integer(10)->unsigned()->notNull(),
"PRIMARY KEY (`post_id`,`loc_id`)",
], 'ENGINE=InnoDB DEFAULT CHARSET=utf8');
This works for me
$this->createTable('new_table',[
'id' => Schema::TYPE_PK.' NOT NULL AUTO_INCREMENT',
'name' => Schema::TYPE_STRING,
'age' => Schema::TYPE_INTEGER
]);
However you can simply use the below style and Yii will replace the 'pk' type of id based on your DBMS. for MYSQL it will be int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
$this->createTable('new_table',[
'id' => 'pk',
'name' => Schema::TYPE_STRING,
'age' => Schema::TYPE_INTEGER
]);
Another (imo more readable) approach is:
$this
->integer()
->unsigned()
->notNull()
->append('AUTO_INCREMENT');
I am using PhPUnit, FactoryMuffin and Faker for testing in Laravel, with a PostgreSQL db. In the previous version of FactoryMuffin (Zizaco\FactoryMuff) I could assign null values to columns both in the static factory array and when calling FactoryMuff::create.
However this no longer works - if I use the following define:
FactoryMuffin::define('MyModel', array(
'name' => 'word',
'empty' => null,
'another' => 'word'
));
when I call FactoryMuffin::create instead of passing NULL to the SQL INSERT statement it leaves the value blank, so I get:
INSERT INTO my_table ("name", "empty", "another") VALUES ('Ralph', , 'Someone');
which PGSQL doesn't allow. The same thing happens using
FactoryMuffin::create('MyModel', array('empty' => null));
Any ideas how to get round this, beyond instantiating the model and then assigning null to the field?
Since FactoryMuffin 2.1 (and 3.*) you can take advantage of the callback functionality, e.g.:
FactoryMuffin::define('MyModel', array(
'name' => 'word',
'empty' => null,
'another' => 'word'
))->setCallback(function ($object, $saved) {
$object->empty = null;
});
In FactoryMuffin 2.1 the callback is set as the third parameter of the define:
FactoryMuffin::define('MyModel', array(
'name' => 'word',
'empty' => null,
'another' => 'word'
), function ($object, $saved) {
$object->empty = null;
});
I'm working on a project and using Yii's Migration feature to keep the different production and test systems in sync. I must say i love this tool.
My question is there a way to create custom Abstract Data Types?
I know Yii's migration feature is made to allow table creation in multiple DBMS systems but my site is limited to MySQL so that should help things along.
What I would like to do is:
$this->createTable('test_table', array(
'key'=>'pk',
'active_YN'=>'yn',
));
instead of:
$this->createTable('test_table', array(
'key'=>'pk',
'active_YN'=>'TINYINT(1) NOT NULL DEFAULT \'1\'',
));
Im guessing that i would have to extend CDbMigration, possibly with a behavior?
Many Thanks.
If you still want to make the trick, here is what you can try.
MySQL uses the driver CMysqlSchema by default. You need to extend this class with your custom abstract column types.
class MyCustomMysqlSchema extends CMysqlSchema
{
/**
* #var array the abstract column types mapped to physical column types.
*/
public $columnTypes=array(
'pk' => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'int(11)',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'timestamp',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'money' => 'decimal(19,4)',
// add your custom abstract column types here
'yn' => 'tinyint(1) UNSIGNED NOT NULL DEFAULT 1',
);
}
You need your connection to use this new driver. Modify your db configuration as follow.
'db'=>array(
// your initial db configuration here
'driverMap'=>array('mysql'=>'MyCustomMysqlSchema'),
),