Lim*_*eat 0 polymorphism one-to-one relationship laravel
我有一对一的多态,我想找出更新现有关系的最佳方式。
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');
}
}
Run Code Online (Sandbox Code Playgroud)
PostController 中的更新方法
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->image()->delete();
$post->image()->save(new Image([
'url'=> $request->input('image_url),
]));
}
Run Code Online (Sandbox Code Playgroud)
如何在不先删除的情况下更新图像关系?
谢谢
您可以尝试updateOrCreate在关系上使用:
$post->image()->updateOrCreate(
[],
['url' => $request->input('image_url')]
);
Run Code Online (Sandbox Code Playgroud)
如果您总是希望有一个Image相关的,Post您可以Image直接更新实例:
$post->image->update([...]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
437 次 |
| 最近记录: |