The Models provides a simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. (The Models are a simplified version of the Laravel Eloquent)
The Models are stored in the app/models
directory. By default there are already defined some models, like the User
model.
class User extends Model {
protected $table = 'users';
}
$users = User::all();
$user = User::find(1);
var_dump($user->username);
Note: All methods available on the query builder are also available when querying Models.
$users = User::where('id', '>', 10)->take(10)->get();
foreach ($users as $user) {
var_dump($user-username);
}
$count = User::where('id', '>', 10)->count();
To create a new record in the database from a model, simply create a new model instance and call the save
method.
$user = new User;
$user->username = 'john';
$user->save();
To update a model, you may retrieve it, change an attribute, and use the save
method:
$user = User::find(1);
$user->email = 'john@foo.com';
$user->save();
You may also run updates as queries against a set of models:
$affectedRows = User::where('id', '>', 10)->update(array('status' => 1));
To delete a model, simply call the delete
method on the instance:
$user = User::find(1);
$user->delete();
Of course, you may also run a delete query on a set of models:
$affectedRows = User::where('id', '>', 10)->delete();