laravel 展开用户模型

wh6knrhe  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(99)

我试图用另一个表(配置文件)来扩展用户模型,以获得配置文件-图片、位置等。
我是否可以覆盖用户模型的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',
    ];
}
nhaq1z21

nhaq1z211#

您尝试在User模型和新的Profile模型之间建立关系。为此,您首先需要创建一个模型Profile及其关联的表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,一切都应按预期运行
如果要测试关系是否按预期工作,请创建一个新的TestCase
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/eloquent-relationships
了解有关迁移的更多信息:https://laravel.com/docs/9.x/migrations

备选

$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.

相关问题