namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model {}
protected $fillable = ['name', 'email', 'password'];
protected $guarded = ['id'];
protected $hidden = ['password', 'remember_token'];
User::create(['name' => 'James', 'email' => '[email protected]']);
$user = User::find(1);
$activeUsers = User::where('status', 'active')->get();
public function posts() {
return $this->hasMany(Post::class);
}
public function profile() {
return $this->hasOne(Profile::class);
}
public function user() {
return $this->belongsTo(User::class);
}
posts
表格可能有一個user_id
欄位,這個欄位指向users
表格的id
欄位,從而建立User
和Post
之間的關聯。當使用Eloquent的關聯方法時,Laravel會自動處理這些外鍵的查詢和更新。$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();