【问题标题】:Update in one to one relation table laravel更新一对一关系表 laravel
【发布时间】:2016-12-17 01:23:48
【问题描述】:

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

旅游:

id|title|content

特色图片:

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. 使用新文件路径更新featured_image 表中的path
  2. 删除旧图片

下面是我更新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 列中。

【问题讨论】:

  • $featured_image->save() 将新位置分配给 path 属性后。 $featured_image->path = $location; $featured_image->save();
  • 我编辑了那个并得到了错误SQLSTATE[HY000]: General error: 1364 Field 'tour_id' doesn't have a default value

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


【解决方案1】:

你应该像这样保存关系:

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

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

【讨论】:

  • 如果 $tour->featuredImage 为空,您可以在更新之前创建新的 featuresImage。像这样: $featuredImage = $tour->featuredImage ? $tour->featuredImage : 新的featuredImage;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 2018-09-26
  • 1970-01-01
  • 2019-03-31
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多