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'];
常用方法
User::create(['name' => 'James', 'email' => 'james@example.com']);
$user = User::find(1);
$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
欄位,從而建立User
和Post
之間的關聯。當使用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方法
$user = new User;
$user->name = 'James';
$user->save();
$user = User::find(1);
$user->delete();
$user = User::find(1);
$user->name = 'James Lee';
$user->update();
$user = User::find(1);
$freshUser = $user->fresh();