The $tablName property is used to tell which table the model will work with. There are also several other properties to customize the model configuration.
Model Properties
$tableName : to define the table name. This property is required.
$tablePrefix : to define a prefix for table names. This property is optional.
$primaryKey : to define the column name of the table's primary key. Default is "id". If your PK has other name than "id" you should change this.
$incrementing : to define whether your PK is auto-increment. Default value is true. If you'd like to generate your Primary Key value by custom function, set this to false.
$post = newPost();
$post->title = 'A New Title';
$post->content = 'More content to come...';
$post->save();
After saving the record, if your model uses an auto incrementing primary key, the generated insert id will be set to the object. So if you use example above, you can show the new post's ID.
1
echo"New Post ID: " . $post->id;
Note
Note that the property isn't always id. It depends on the primaryKey property you've set.
Alternatively, you can use create() method to create new models.
1234
$post = Post::create( ['title' => 'A New Title', 'content' => 'More content to come...'] );
// create() method will return a newly created model or false if inserting failsecho$post->id;
Updating Models
Updating Retrieved Models
1234
$post = Post::find(1);
$post-title = 'A Different Title';
$post->save();
Mass Updating
You still can use Active Record to generate a custom query before updating.
1
Post::where('status', 'published')->update( ['title' => 'A Different Title'] );
Or alternatively you can call update() method right away.
1
Post::update( ['title' => 'A Different Title'], ['id' => 1] );
Deleting Models
There are several ways to delete model
1 2 3 4 5 6 7 8 91011121314
// Delete retrieved model$post = Post::find(1);
$post->delete();
// Delete a single model by its primary keyPost::delete(1);
// Delete multiple models by their primary keysPost::delete(1, 2, 3);
//orPost::delete( [1, 2, 3] );
// Use Active RecordPost::where('status', 'published')->delete();