Laravel初學者指南:深入探索Model的使用與應用

2023/08/18閱讀時間約 4 分鐘

Model的基本屬性與方法

  • Model的角色:在Laravel中,Model代表資料庫中的表格,並使用Eloquent ORM來操作這些表格。
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model {}

常用屬性

  • `$fillable`:定義哪些欄位可以被批量賦值。
protected $fillable = ['name', 'email', 'password'];
  • `$guarded`:定義哪些欄位不可以被批量賦值。
protected $guarded = ['id'];
  • `$hidden`:在模型數組或JSON顯示中隱藏某些屬性。
protected $hidden = ['password', 'remember_token'];

常用方法

  • `create()`:建立新的資料庫紀錄。
User::create(['name' => 'James', 'email' => '[email protected]']);
  • `find()`:根據主鍵查找紀錄。
$user = User::find(1);
  • `where()`:基於給定條件查找紀錄。
$activeUsers = User::where('status', 'active')->get();


Model關聯:hasMany、hasOne、belongsTo

  • hasMany:一對多的關聯。例如,一個`User`模型可能有多個`Post`。
public function posts() {

return $this->hasMany(Post::class);

}


  • hasOne:一對一的關聯。例如,一個`User`模型可能只有一個`Profile`。
public function profile() {

return $this->hasOne(Profile::class);

}

  • belongsTo:多對一的關聯。例如,多個`Post`可能屬於同一個`User`。
public function user() {

return $this->belongsTo(User::class);

}
  • 關聯的依據:上述這些方法,在Laravel中,這些關聯是基於資料庫中的外鍵來建立的。例如,posts表格可能有一個user_id欄位,這個欄位指向users表格的id欄位,從而建立UserPost之間的關聯。當使用Eloquent的關聯方法時,Laravel會自動處理這些外鍵的查詢和更新。


如何呼叫Model

  • 導入Model:在控制器或其他PHP文件中,使用`use`語句來導入Model。例如,`use App\Models\User;`。
  • 操作資料庫表格:通過Model名稱來操作對應的資料庫表格。例如,`User::all()`來獲取所有用戶。
  • 動態屬性:Laravel允許您使用動態屬性訪問資料庫表格的欄位。例如,`$user->name`可以獲取用戶的名稱。
  • 使用查詢建構器:Model提供了查詢建構器,使得資料庫操作更加直觀。例如,`User::where('account_status', 'active')->get();`。


相關的Model方法

  • `save()`:保存模型的新實例到資料庫。
$user = new User;

$user->name = 'James';

$user->save();


  • `delete()`:從資料庫中刪除模型。
  $user = User::find(1);

$user->delete();


  • `update()`:更新資料庫中的模型。
$user = User::find(1);

$user->name = 'James Lee';

$user->update();


  • `fresh()`:從資料庫重新檢索模型。
$user = User::find(1);

$freshUser = $user->fresh();
Laravel專案開發系列作為初學者和追求卓越的開發者的指南。從Laravel的基礎語法開始,逐步深入到實際的應用開發,如購物車系統。這系列不僅助您打好基礎,更能夠引領您走向專業開發的道路,讓您在Laravel的世界中游刃有餘。
留言0
查看全部
發表第一個留言支持創作者!