- What's new in ❊ Perpl ❊
- ❊ Perpl ❊ Changelog
- What's new in Propel 2.0
- Propel API Documentation
- Installing Propel
- Building a project
- Basic CRUD
- Relationships
- Transactions
- Behaviors
- Logging And Debugging
- Inheritance
- Migrations
- Configuration
- XML Schema Format
- Active Record Classes
- Active Query Classes
- Configuration Properties Reference
- Compatibility index
- Writing A Behavior
- aggregate_column
- archivable
- auto_add_pk
- config_store
- delegate
- i18n
- nested_set
- query_cache
- sluggable
- timestampable
- sortable
- validate
- versionable
- concrete_inheritance
- User-Contributed Behaviors
- Working With Propel's Test Suite
- Additional SQL Files
- Advanced Column Types
- How to Use Namespaces
- Model Introspection At Runtime
- Multi-Component Data Model
- Object Copy
- Replication
- Using Propel With MSSQL Server
- Using SQL Schemas
- Working With Existing Databases
- Working with Symfony2
- Working with Silex
Setup
Basics
Reference
Behaviors
Cookbook
AutoAddPk Behavior
The auto_add_pk
behavior adds a primary key columns to the tables that don’t have one. Using this behavior allows you to omit the declaration of primary keys in your tables.
Basic Usage
In the schema.xml
, use the <behavior>
tag to add the auto_add_pk
behavior to a table:
<table name="book">
<column name="title" type="varchar" required="true" primaryString="true" />
<behavior name="auto_add_pk" />
</table>
Rebuild your model, and insert the table creation sql. You will notice that the book
table has two columns and not just one. The behavior added an id
column, of type integer and autoincremented. This column can be used as any other column:
<?php
$b = new Book();
$b->setTitle('War And Peace');
$b->save();
echo $b->getId(); // 1
This behavior is more powerful if you add it to the database instead of a table. That way, it will alter all tables not defining a primary key column - and leave the others unchanged.
<database name="bookstore" defaultIdMethod="native">
<behavior name="auto_add_pk" />
<table name="book">
<column name="title" type="varchar" required="true" primaryString="true" />
</table>
</database>
Parameters
By default, the behavior adds a column named id
to the table if the table has no primary key. You can customize all the attributes of the added column by setting corresponding parameters in the behavior definition:
<database name="bookstore" defaultIdMethod="native">
<behavior name="auto_add_pk">
<parameter name="name" value="identifier" />
<parameter name="autoIncrement" value="false" />
<parameter name="type" value="bigint" />
</behavior>
<table name="book">
<column name="title" type="varchar" required="true" primaryString="true" />
</table>
</database>
Once you regenerate your model, the column is now named differently:
<?php
$b = new Book();
$b->setTitle('War And Peace');
$b->setIdentifier(1);
$b->save();
echo $b->getIdentifier(); // 1