Tingkatkan model pengguna
P粉311464935
P粉311464935 2024-01-10 17:17:58
0
1
281

Saya cuba memanjangkan model Pengguna dengan jadual lain (Profil) untuk mendapatkan gambar profil, lokasi, dsb.

Bolehkah saya mengatasi fungsi index() model Pengguna untuk melakukan ini?

Kod model semasa:

<?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

membalas semua(1)
P粉378890106

Apa yang anda mahu lakukan adalah dalam User 模型和新的Profile 模型之间建立关系。为此,您首先需要创建一个模型 Profile 及其关联的 Tabble profiles

php artisan make:model Profile --migration

Fail dalam databasemigrations中应该有一个名为2022_11_28_223831_create_profiles_table.php

Sekarang anda perlu menambah kunci asing untuk menunjukkan pengguna yang mempunyai profil ini.

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();
    });
}

Sekarang tambah fungsi berikut dalam model pengguna anda

public function profile()
{
    return $this->hasOne(Profile::class);
}

Dalam model profil anda

public function user()
{
    return $this->belongsTo(User::class);
}

Larikanphp artisan migrate dan semuanya harus berfungsi seperti yang diharapkan

Jika anda ingin menguji sama ada hubungan itu berfungsi seperti yang diharapkan, buat kes ujian baharu

php artisan make:test ProfileUserRelationTest

di testsFeatureProfileUserRelationTest.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);
    }
}

Kini anda boleh berlari php artisan test untuk melihat sama ada semuanya baik-baik saja.

AwasIni akan menyegarkan pangkalan data anda! Jadi jangan uji dalam pengeluaran.

Keluaran sepatutnya kelihatan seperti ini

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

Ketahui lebih lanjut tentang perhubungan dalam Laravel: https://laravel.com/docs/9.x/eloquent-relationships

Ketahui lebih lanjut tentang migrasi: https://laravel.com/docs/9.x/migrations

Alternatif

$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.
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!