Laravel 關聯 Model

Laravel 關聯性Model基礎操作:belongs_to, has_one, has_many, many to many 1. 一對一關係 has_one 假設兩個Model:店主Owner、商店Store,店主擁有一間商店(Owner has one Store),商店屬於一位店主(Store belongs to Owner)。 Owner: - id - name Store: - id - name - owner_id 首先要為Store創建欄位owner_id,在migration中可以使用$table->foreignId('owner_id')建立欄位(foreignId等同於unsignedBigInt)。 Owner.php中寫入hasOne: // app/Models/Owner.php public function store() { return $this->hasOne(Store::class); } Store.php中寫入belonsTo: // app/Models/Store.php public function owner() { return $this->belongsTo(Owner::class); } 使用方法: // 從Owner角度建立Store // 方法一:使用create $o1 = Owner::find(1); $o1->store()->create(['name'=>'store1']); // 方法二:使用save $o1 = Owner::find(1); $s2 = new Store(['name'=?'store2']); $o1->store()->save($s2); // 從Store角度建立Owner $o2 = Owner::find(2); $s3 = new Store(['name'=>'store3']); $s3->owner()->associate($o2); $s3->save(); // 撈取該Owner的Store $o1->store; $o1->store->name; // 撈取該Store的Owner $s1->owner; $s1->owner->name; hasOne與belongsTo都可以獨立設置foreign key或owner key:...

January 19, 2024 · 295 words · HSIAO, YI-HUSAN