Home >PHP Framework >Laravel >ORM (Object Relational Mapping) in Laravel: Manipulate databases elegantly
ORM (Object Relational Mapping) in Laravel: Manipulate the database elegantly
Introduction:
During the development process, interaction with the database is inevitable part. Using ORM (Object Relational Mapping) allows us to operate the database in an object-oriented manner without writing cumbersome SQL statements. The Laravel framework provides powerful and elegant ORM tools to facilitate developers to perform database operations. This article will introduce the use of ORM in Laravel, with code examples.
1. ORM in Laravel
ORM is a technology that maps objects to tables in a relational database and the relationships between tables. Using ORM, we can directly add, delete, modify, and query the database by operating objects without having to process the underlying SQL statements. The ORM in Laravel is implemented using Eloquent, which is a simple, elegant and powerful ORM tool.
Advantages:
2. Basic use of Eloquent ORM
For example, if we have a users data table, then we can create a User model to correspond to it:
namespace App; use IlluminateDatabaseEloquentModel; class User extends Model { // 指定数据表名 protected $table = 'users'; }
Get all records:
$users = User::all();
Get the first record:
$user = User::first();
Search for records based on primary key:
$user = User::find(1);
Search for records based on conditions:
$users = User::where('age', '>', 18)->get();
Add record:
$user = new User; $user->name = 'Tom'; $user->age = 20; $user->save();
Update record:
$user = User::find(1); $user->age = 25; $user->save();
Delete record:
$user = User::find(1); $user->delete();
Association:
Laravel's ORM supports association operations between database tables, such as one-to-one, one-to-many, many-to-many, etc.
Taking one-to-many association as an example, we can define two models (User and Post), and define a one-to-many relationship with the Post model in the User model:
namespace App; use IlluminateDatabaseEloquentModel; class User extends Model { // 定义与Post模型的一对多关系 public function posts() { return $this->hasMany('AppPost'); } }
Then, we can Get all the user's articles in the following way:
$user = User::find(1); $posts = $user->posts;
Summary:
The ORM (Object Relational Mapping) in Laravel provides an elegant and powerful tool to facilitate developers to perform database operations. . By using ORM, we can simplify the process of database operations and develop in an object-oriented manner. This article introduces the basic use of ORM in Laravel and attaches code examples. I hope it will be helpful to readers. If you haven't used Laravel's ORM yet, you might as well try it. I believe you will fall in love with its simplicity and elegance.
Reference:
The above is the detailed content of ORM (Object Relational Mapping) in Laravel: Manipulate databases elegantly. For more information, please follow other related articles on the PHP Chinese website!