Laravel開發(fā):如何使用Laravel Eloquent構(gòu)建數(shù)據(jù)庫模型?

laravel開發(fā):如何使用laravel eloquent構(gòu)建數(shù)據(jù)庫模型?

Laravel是一款廣受歡迎的PHP框架,其提供了強(qiáng)大且易于使用的數(shù)據(jù)庫操作工具——Laravel Eloquent。在過去,要使用PHP進(jìn)行數(shù)據(jù)庫操作難免要寫大量冗長的SQL語句和繁瑣的代碼,而使用Laravel Eloquent則能夠輕松地構(gòu)建數(shù)據(jù)庫模型,實現(xiàn)快速開發(fā)和維護(hù)。本文將介紹如何使用Laravel Eloquent構(gòu)建數(shù)據(jù)庫模型。

一、創(chuàng)建數(shù)據(jù)庫表

首先,需要通過數(shù)據(jù)庫遷移(Migration)創(chuàng)建數(shù)據(jù)庫表。在Laravel中,可以使用命令行工具artisan來實現(xiàn)此過程。在命令行中輸入:

php artisan make:migration create_users_table

該命令會在app/database/migrations目錄下創(chuàng)建一個遷移文件,文件名稱為當(dāng)前日期和時間加上遷移的名稱,例如2019_08_17_000000_create_users_table.php。修改遷移文件,編寫對應(yīng)的數(shù)據(jù)庫結(jié)構(gòu)。

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(); });

以上代碼創(chuàng)建了一個名為users的表,其中包含了id、name、email、email_verified_at、password、remember_token、created_at和updated_at共8個字段。接下來,運行遷移文件,創(chuàng)建數(shù)據(jù)庫表。

php artisan migrate

二、創(chuàng)建模型

在應(yīng)用中創(chuàng)建模型(Model)是使用Laravel Eloquent的第一步。可以通過artisan工具來創(chuàng)建一個模型:

php artisan make:model User

上面的命令將在app目錄下創(chuàng)建一個名為User的模型,該模型對應(yīng)著數(shù)據(jù)庫中的users表。默認(rèn)情況下,Laravel Eloquent假定數(shù)據(jù)庫表名是模型名稱的復(fù)數(shù)形式,如果需要對應(yīng)的是不同的表名或使用不同的數(shù)據(jù)庫連接,可以在模型中定義屬性$table和$connection。

模型的定義如下:

namespace App;  use IlluminateDatabaseEloquentModel;  class User extends Model {     // }

三、模型屬性

在模型中,Laravel Eloquent已定義了一些默認(rèn)屬性和方法,其中包括:

  1. $fillable屬性:定義可以被批量賦值的屬性,以防止注入攻擊。可以從創(chuàng)建/更新的請求中使用create()和update()方法進(jìn)行填充。
protected $fillable = [     'name', 'email', 'password', ];
  1. $hidden屬性:定義應(yīng)在數(shù)組中隱藏的屬性。當(dāng)進(jìn)行序列化操作時,這些屬性將被隱藏。
protected $hidden = [     'password', 'remember_token', ];
  1. $casts屬性:定義屬性應(yīng)被轉(zhuǎn)化為原生類型(整型、布爾型、浮點型等)或自定義的對象。
protected $casts = [     'email_verified_at' => 'datetime', ];

四、模型方法

Laravel Eloquent提供了一些方法,以便在模型中進(jìn)行數(shù)據(jù)操作。以下是一些最常見的模型方法:

  1. where():用于添加WHERE條件。
$user = User::where('name', 'John')->first();
  1. find():用于通過模型的主鍵ID查找記錄。
$user_id = 1; $user = User::find($user_id);
  1. first():返回第一個查找到的記錄。
$user = User::where('name', 'John')->first();
  1. get():返回查找到的所有記錄。
$users = User::all();
  1. create():用于創(chuàng)建一條新的數(shù)據(jù)記錄。
User::create(['name' => 'Taylor', 'email' => 'taylor@example.com', 'password' => 'password']);
  1. update():用于更新記錄。
$user = User::find($user_id); $user->name = 'Updated Name'; $user->save();
  1. delete():用于刪除記錄。
$user = User::find($user_id); $user->delete();

以上是一些基本的Laravel Eloquent模型方法,可以快速的實現(xiàn)對數(shù)據(jù)庫的增、刪、改、查操作。

五、關(guān)聯(lián)關(guān)系

Laravel Eloquent還提供了一種便捷的方式來定義各種關(guān)聯(lián)性:一對一(One to One)、一對多(One to Many)、多對多(Many to Many)和多態(tài)關(guān)聯(lián)(Polymorphic Relations)。以下是一些例子:

  1. 一對一(One to One)

在一對一的關(guān)聯(lián)關(guān)系中,每個模型實例只與另一個相關(guān)模型實例相關(guān)聯(lián)。例如,在users表中的每行數(shù)據(jù)都可能與一個phone表中的行相關(guān)聯(lián),phone表存儲了用戶的電話號碼。在User模型中,定義一個phone()方法,表示該模型與phone模型之間的一對一關(guān)系。

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

在Phone模型中,定義相反的hasOne()方法。

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

在一對多的關(guān)聯(lián)關(guān)系中,一個模型實例與另一個模型實例相關(guān)聯(lián),而另一個實例可以關(guān)聯(lián)多個模型實例。例如,在一個論壇網(wǎng)站中,每個模板可能與許多評論相關(guān)聯(lián)。在Thread模型中,定義一個comments()方法,表示該模型與Comment模型之間的一對多關(guān)系。

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

在Comment模型中,定義相反的belongsTo()方法。

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

在多對多的關(guān)聯(lián)關(guān)系中,該模型實例與許多其他模型實例相關(guān)聯(lián),而每個相關(guān)的模型實例也可以與多個模型實例關(guān)聯(lián)。例如,在一個博客中,每篇文章可能有多個分類標(biāo)簽,每個標(biāo)簽也可能有多篇文章。在Post模型中,定義一個tags()方法,表示該模型與Tag模型之間的多對多關(guān)系。

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

在Tag模型中,定義相反的belongsToMany()方法。

class Tag extends Model {     public function posts()     {         return $this->belongsToMany('AppPost');     } }
  1. 多態(tài)關(guān)聯(lián)(Polymorphic Relations)

多態(tài)關(guān)聯(lián)允許模型通過多個中介模型與其他模型進(jìn)行多對多關(guān)聯(lián)。例如,在應(yīng)用中可以使用comments模型對其他類型的模型進(jìn)行評論。在Comment模型中,定義一個commentable()方法,表示該模型與所有支持評論的模型之間的多態(tài)關(guān)系。

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提供的關(guān)聯(lián)關(guān)系,可以讓開發(fā)者在數(shù)據(jù)庫模型中輕松處理復(fù)雜的關(guān)系結(jié)構(gòu)。

七、總結(jié)

本文介紹了使用Laravel Eloquent構(gòu)建數(shù)據(jù)庫模型的基礎(chǔ)知識,包括創(chuàng)建數(shù)據(jù)庫表、創(chuàng)建模型、模型屬性和方法,以及關(guān)聯(lián)關(guān)系。Laravel Eloquent提供了一種簡單和直觀的方式來操作數(shù)據(jù)庫,使得開發(fā)者能夠快速構(gòu)建應(yīng)用程序,并為復(fù)雜的數(shù)據(jù)庫結(jié)構(gòu)提供了更干凈、易于維護(hù)的解決方案。希望這篇文章對你的學(xué)習(xí)和開發(fā)有所幫助。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊12 分享