更新一对一关系 table laravel

Update in one to one relation table laravel

我有 2 个 table 是一对一的关系:

游览:

id|title|content

featured_image:

id|tour_id|name|path

我的模特FeaturedImage.php:

class FeaturedImage extends Model
{
protected $fillables = [
    'name',
    'path',
    'tour_id',
];

public function tour()
 {
  return $this->belongsTo('App\Tour');
 }
}

Tours.php

class Tour extends Model
{
protected $fillables = [
    'title',
    'content',
];

public function featuredImage()
 {
  return $this->hasOne('App\FeaturedImage');
 }
}

我正在尝试更新 featured_image table 上传新的游览图片:

  1. 使用新文件路径
  2. 更新featured_imagetable中的path
  3. 删除旧图像

下面是我更新featured_image路径栏的方法:

// update featured image       
    if ($request->hasFile('featured_image')) {
    $featured_image= new FeaturedImage;
// add the new photo
    $image = $request->file('featured_image');
    $filename = $image->getClientOriginalName();
    $location = 'images/featured_image/'.$filename; 
    //dd($location);
    Image::make($image)->resize(800, 400)->save($location);

    $oldFilename= $tour->featuredImage->path;
// update the database
    $featured_image->path = $location;
// Delete the old photo
    File::delete(public_path($oldFilename));
    }

以上代码成功删除旧图片并上传新图片,但未能更新路径列。我 运行 dd($location);,它给出了新图像的路径,但没有保存在数据库列中。

你应该这样保存关系:

$featuredImage = $tour->featuredImage;
$featuredImage->path = $location;
$tour->featuredImage()->save($featuredImage);

https://laravel.com/docs/5.3/eloquent-relationships#the-save-method