我正在尝试使用另一个表(个人资料)扩展用户模型以获取个人资料图片、位置等。
我可以重写用户模型的 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',
];
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您想要做的是在
User模型和新的Profile模型之间建立关系。为此,您首先需要创建一个模型Profile及其关联的 Tabbleprofilesphp 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来查看是否一切正常。小心这会刷新您的数据库!所以不要在生产中进行测试。
输出应该是这样的
了解有关 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.