【问题标题】:What is the best way to update One to One Polymorphic in Laravel?在 Laravel 中更新一对一多态的最佳方法是什么?
【发布时间】:2020-04-16 18:57:03
【问题描述】:

我有一对一的多态,我想找出更新现有关系的最佳方法。

class Image extends Model
{
    /**
     * Get the owning imageable model.
     */
    public function imageable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get the post's image.
     */
    public function image()
    {
        return $this->morphOne('App\Image', 'imageable');
    }
}

class User extends Model
{
    /**
     * Get the user's image.
     */
    public function image()
    {
        return $this->morphOne('App\Image', 'imageable');
    }
}

关于 PostController 中的更新方法

public function update(Request $request, $id)
{
    $post       = Post::findOrFail($id);
    $post->image()->delete();
    $post->image()->save(new Image([
        'url'=> $request->input('image_url),
    ]));
}

如何在不先删除的情况下更新图像关系?

谢谢

【问题讨论】:

  • aPost 是否总是已经有使用此方法的图像?
  • 是的,总是有图片。

标签: laravel polymorphism relationship one-to-one


【解决方案1】:

您可以尝试在关系上使用updateOrCreate

$post->image()->updateOrCreate(
    [],
    ['url' => $request->input('image_url')]
);

如果您一直期望有一个与Post 相关的Image,您可以直接更新Image 实例:

$post->image->update([...]);

【讨论】:

  • 你的意思是$post->image()->updateOrCreate( ['imagable_type' => 'App\Post', 'imageable_id' => $post->id], ['url' => $request->input('image_url')] );
  • 不,关系应该在执行选择查询时添加所需的变形字段
  • 我收到此错误message: "Call to a member function updateOrCreate() on null",因为我希望它在数据库中的关系记录中创建 if。
  • 如果有关系记录,updateOrCreate(),只作为更新方式,没有记录就创建。
  • 你在叫什么updateOrCreate$post->image() 不应返回 null
猜你喜欢
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多