我试图用另一个表(配置文件)来扩展用户模型,以获得配置文件-图片、位置等。
我是否可以覆盖用户模型的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',
];
}
1条答案
按热度按时间nhaq1z211#
您尝试在
User
模型和新的Profile
模型之间建立关系。为此,您首先需要创建一个模型Profile
及其关联的表profiles
php artisan make:model Profile --migration
在
database\migrations
中应该有一个类似于2022_11_28_223831_create_profiles_table.php
的文件现在,您需要添加一个外键,以指示此配置文件属于哪个用户。
现在,在用户模型中添加以下函数
在您的配置文件模型中
运行
php artisan migrate
,一切都应按预期运行如果要测试关系是否按预期工作,请创建一个新的TestCase
php artisan make:test ProfileUserRelationTest
以
tests\Feature\ProfileUserRelationTest.php
为单位现在,您可以运行
php artisan test
来查看是否一切正常。小心**这将刷新您的数据库!**因此不要在生产环境中进行测试。
输出应该如下所示
了解更多关于Laravel的关系:https://laravel.com/docs/9.x/eloquent-relationships
了解有关迁移的更多信息:https://laravel.com/docs/9.x/migrations
备选