Benutzermodell verbessern
P粉311464935
P粉311464935 2024-01-10 17:17:58
0
1
310

Ich versuche, das Benutzermodell um eine weitere Tabelle (Profil) zu erweitern, um das Profilbild, den Standort usw. abzurufen.

Kann ich dazu die Funktion index() des Benutzermodells überschreiben?

Aktueller Modellcode:

<?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粉311464935
P粉311464935

Antworte allen(1)
P粉378890106

您想要做的是在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.
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!