我正在嘗試使用另一個表(個人資料)擴展用戶模型以獲取個人資料圖片、位置等。
我可以重寫使用者模型的 index()
函數來做到這一點嗎?
目前型號代碼:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; protected $fillable = [ 'name', 'email', 'password', 'user_group' ]; protected $hidden = [ 'password', 'remember_token', ]; protected $casts = [ 'email_verified_at' => 'datetime', ]; }
P粉3788901062024-01-11 15:21:01
您想要做的是在User
模型和新的Profile
模型之間建立關係。為此,您首先需要建立一個模型 Profile
及其關聯的 Tabble profiles
php artisan make:model Profile --migration
在database\migrations
中應該有一個名為2022_11_28_223831_create_profiles_table.php
現在您需要新增一個外鍵來指示此設定檔屬於哪個使用者。
public function up() { Schema::create('profiles', function (Blueprint $table) { $table->id(); // $table->string('path_to_picture') // user id $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); }
現在在您的使用者模型中加入以下函數
public function profile() { return $this->hasOne(Profile::class); }
在您的個人資料模型中
public function user() { return $this->belongsTo(User::class); }
運行php artisan migrate
,一切都應該按預期工作
如果您想測試關係是否如預期運作,請建立一個新的測試案例
php artisan make:test ProfileUserRelationTest
#在tests\Feature\ProfileUserRelationTest.php
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; use App\Models\User; use App\Models\Profile; use Illuminate\Support\Facades\Hash; class ProfileUserRelationTest extends TestCase { use RefreshDatabase; public function test_the_relation_between_user_and_profile_works() { $user = User::create([ 'name' => 'John Doe', 'email' => 'jd@example.com', 'password' => Hash::make('password'), ]); $profile = new Profile(); $profile->user_id = $user->id; $profile->save(); $this->assertEquals($user->id, $profile->user->id); $this->assertEquals($user->name, $profile->user->name); $this->assertEquals($profile->id, $user->profile->id); } }
現在您可以執行 php artisan test
來查看是否一切正常。
小心這會刷新您的資料庫! 所以不要在生產中進行測試。
輸出應該是這樣的
PASS Tests\Unit\ExampleTest ✓ that true is true PASS Tests\Feature\ExampleTest ✓ the application returns a successful response PASS Tests\Feature\ProfileUserRelationTest ✓ the relation between user and profile works Tests: 3 passed Time: 0.35s
了解有關 Laravel 中關係的更多資訊:https://laravel.com/docs/ 9.x/雄辯關係
了解更多有關遷移的資訊:https://laravel.com/docs/9.x/遷移
替代方案
$user = User::create([ 'name' => 'John Doe', 'email' => 'jd@example.com', 'password' => Hash::make('password'), ]); $user->profile()->create(...); // replace the ... with the things you want to insert you dont need to add the user_id since it will automatically added it. It will still work like the one above.