更新一对一关系表laravel

时间:2016-12-16 17:13:59

标签: php laravel blade laravel-5.3 laravel-blade

我有两个一对一关系的表:

参观:

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表格:

  1. 使用新文件的路径更新path表中的featured_image
  2. 删除旧图片
  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);,它给出了新图像的路径但不保存在db列中。

1 个答案:

答案 0 :(得分:2)

你应该保存这样的关系:

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

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