【发布时间】: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 表:
- 使用新文件路径更新
featured_image表中的path列 - 删除旧图片
下面是我更新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