Php 更新一对一关系表laravel
我有两个一对一关系的表: 旅游:Php 更新一对一关系表laravel,php,laravel,blade,laravel-5.3,laravel-blade,Php,Laravel,Blade,Laravel 5.3,Laravel Blade,我有两个一对一关系的表: 旅游: id | title | content 特色图片: id |旅游| id |姓名|路径 My models FeaturedImage.php: class FeaturedImage extends Model { protected $fillables = [ 'name', 'path', 'tour_id', ]; public function tour() { return $this->belongsTo(
id | title | content
特色图片:
id |旅游| id |姓名|路径
My models 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');
}
}
上传旅游新图像时,我正在尝试更新特色图片
表:
特色图片
表中的路径
列特色图片
路径列的方法:
// 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)代码>,它给出了新图像的路径,但没有;t保存在db列中。您应该像这样保存关系:
$featuredImage = $tour->featuredImage;
$featuredImage->path = $location;
$tour->featuredImage()->save($featuredImage);
$characterized\u image->save()
将新位置分配给路径
属性后<代码>$featured_image->path=$location$特色图片->保存()代码>我编辑了它并得到了错误SQLSTATE[HY000]:一般错误:1364字段“tour\u id”没有默认值
如果$tour->featuredImage为空,您可以在更新之前创建新的featuredImage。像这样:$featuredImage=$tour->featuredImage$旅游->特色图片:新特色图片;