Нужно сохранить внешний ключ вручную для связи с withDefault ()? - PullRequest
0 голосов
/ 31 марта 2020

мне кажется, что мне нужно сохранить исходную модель на вновь созданной модели, чтобы правильно сохранить отношение.

Я надеюсь, что приведенный ниже тест иллюстрирует мою проблему:

// migrations
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->bigInteger('user_id')->nullable();
    $table->timestamps();
});

//models
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class)
            ->withDefault(['name' => 'Guest User']);
    }
}

//test
public function test_foreign_key()
{
    $post = factory(Post::class)->create();

    $user = $post->user; // created from ->withDefault()
    $user->save();
    $this->assertNotNull($post->user);
    $this->assertNotNull($post->user_id);
}

При дополнительном сопоставлении исходной модели тест проходит:

public function test_foreign_key_associates()
{
    $post = factory(Post::class)->create();

    $post->user->save();
    $this->assertNotNull($post->user);
    $post->user()->associate($post);
    $this->assertNotNull($post->user_id);
}

edit: сейчас я делаю следующее для отношения withDefault:

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class)
            ->withDefault(function (User $user, Post $post) {
                $user->name = "Guest User";
                $user->save();
                $post->user_id = $user->id;
            });
    }
}
...