Home >PHP Framework >Laravel >Laravel development: How to build a database model using Laravel Eloquent?

Laravel development: How to build a database model using Laravel Eloquent?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2023-06-14 08:21:391533browse

Laravel development: How to build a database model using Laravel Eloquent?

Laravel is a popular PHP framework that provides a powerful and easy-to-use database operation tool - Laravel Eloquent. In the past, using PHP to perform database operations inevitably required writing a large number of lengthy SQL statements and cumbersome codes. However, using Laravel Eloquent can easily build database models and achieve rapid development and maintenance. This article will introduce how to use Laravel Eloquent to build a database model.

1. Create a database table

First, you need to create a database table through database migration (Migration). In Laravel, this process can be achieved using the command line tool artisan. Enter in the command line:

php artisan make:migration create_users_table

This command will create a migration file in the app/database/migrations directory. The file name is the current date and time plus the name of the migration, such as 2019_08_17_000000_create_users_table.php. Modify the migration file and write the corresponding database structure.

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

The above code creates a table named users, which contains 8 fields: id, name, email, email_verified_at, password, remember_token, created_at and updated_at. Next, run the migration file to create the database tables.

php artisan migrate

2. Create a model

Creating a model (Model) in an application is the first step in using Laravel Eloquent. You can create a model through the artisan tool:

php artisan make:model User

The above command will create a model named User in the app directory, which corresponds to the users table in the database. By default, Laravel Eloquent assumes that the database table name is the plural form of the model name. If you need to correspond to a different table name or use a different database connection, you can define the attributes $table and $connection in the model.

The definition of the model is as follows:

namespace App;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    //
}

3. Model properties

In the model, Laravel Eloquent has defined some default properties and methods, including:

  1. $fillable attribute: Define attributes that can be assigned in batches to prevent injection attacks. Can be populated from a create/update request using the create() and update() methods.
protected $fillable = [
    'name', 'email', 'password',
];
  1. $hidden attribute: Defines the attributes that should be hidden in the array. When serializing, these properties will be hidden.
protected $hidden = [
    'password', 'remember_token',
];
  1. $casts attribute: Defines whether the attribute should be converted to a native type (integer, Boolean, floating point, etc.) or a custom object.
protected $casts = [
    'email_verified_at' => 'datetime',
];

4. Model methods

Laravel Eloquent provides some methods to perform data operations in the model. Here are some of the most common model methods:

  1. where(): used to add WHERE conditions.
$user = User::where('name', 'John')->first();
  1. find(): Used to find records by the primary key ID of the model.
$user_id = 1;
$user = User::find($user_id);
  1. first(): Returns the first found record.
$user = User::where('name', 'John')->first();
  1. get(): Returns all the records found.
$users = User::all();
  1. create(): used to create a new data record.
User::create(['name' => 'Taylor', 'email' => 'taylor@example.com', 'password' => 'password']);
  1. update(): used to update records.
$user = User::find($user_id);
$user->name = 'Updated Name';
$user->save();
  1. delete(): used to delete records.
$user = User::find($user_id);
$user->delete();

The above are some basic Laravel Eloquent model methods, which can quickly implement add, delete, modify, and query operations on the database.

5. Association relationship

Laravel Eloquent also provides a convenient way to define various relationships: one-to-one (One to One), one-to-many (One to Many) , Many to Many and Polymorphic Relations. Here are some examples:

  1. One to One

In a one-to-one association, each model instance is only related to one other model Instances are associated. For example, each row in the users table may be associated with a row in the phone table, which stores the user's phone number. In the User model, define a phone() method to represent the one-to-one relationship between the model and the phone model.

class User extends Model
{
    public function phone()
    {
        return $this->hasOne('AppPhone');
    }
}

In the Phone model, define the opposite hasOne() method.

class Phone extends Model
{
    public function user()
    {
        return $this->belongsTo('AppUser');
    }
}
  1. One to Many

In a one-to-many relationship, one model instance is associated with another model instance, and the other An instance can be associated with multiple model instances. For example, in a forum site, each template might be associated with many comments. In the Thread model, define a comments() method to represent the one-to-many relationship between the model and the Comment model.

class Thread extends Model
{
    public function comments()
    {
        return $this->hasMany('AppComment');
    }
}

In the Comment model, define the opposite belongsTo() method.

class Comment extends Model
{
    public function thread()
    {
        return $this->belongsTo('AppThread');
    }
}
  1. Many to Many

In a many-to-many relationship, the model instance is associated with many other model instances, and each Related model instances can also be associated with multiple model instances. For example, in a blog, each article may have multiple category tags, and each tag may also have multiple articles. In the Post model, define a tags() method to represent the many-to-many relationship between the model and the Tag model.

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany('AppTag');
    }
}

In the Tag model, define the opposite belongsToMany() method.

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany('AppPost');
    }
}
  1. 多态关联(Polymorphic Relations)

多态关联允许模型通过多个中介模型与其他模型进行多对多关联。例如,在应用中可以使用comments模型对其他类型的模型进行评论。在Comment模型中,定义一个commentable()方法,表示该模型与所有支持评论的模型之间的多态关系。

class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

在支持评论的模型中,例如Post和Video模型中,定义morphMany()方法。

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany('AppComment', 'commentable');
    }
}

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany('AppComment', 'commentable');
    }
}

以上是Laravel Eloquent提供的关联关系,可以让开发者在数据库模型中轻松处理复杂的关系结构。

七、总结

本文介绍了使用Laravel Eloquent构建数据库模型的基础知识,包括创建数据库表、创建模型、模型属性和方法,以及关联关系。Laravel Eloquent提供了一种简单和直观的方式来操作数据库,使得开发者能够快速构建应用程序,并为复杂的数据库结构提供了更干净、易于维护的解决方案。希望这篇文章对你的学习和开发有所帮助。

The above is the detailed content of Laravel development: How to build a database model using Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn