我有两个属于一对多关系的模型:
Tour.php
public function photos()
{
return $this->hasMany('App\Photo');
}
Photo.php
public function tour()
{
return $this->belongsTo('App\Tour');
}
我想删除与这些照片相关的游览时从文件夹中删除这些照片。这些照片位于(公共/图像/幻灯片)
中这就是我试图做的事情:
public function destroy($id)
{
$tour = Tour::find($id);
$tour->country()->detach();
File::delete(public_path('/images/featured_image/'.$tour->featured_image));
File::delete(public_path('/images/banner/'.$tour->banner));
File::delete(public_path('/images/slides/'.$tour->photos->path));
$tour->delete();
Session::flash('success', 'The tour is sucessfully deleted.');
return redirect()->route('tours.index');
}
我得到错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$path
答案 0 :(得分:0)
由于$tour->photos
是一个集合,因此您无法访问集合中的一个属性。
你需要运行一个循环
foreach($tour->photos() as $photo){
File::delete(public_path($photo->path));
}
但我会采用不同的方式
On You Tour Model (Tour.php)
创建启动方法
protected static function boot() {
parent::boot();
static::deleting(function($tour) {
$tour->photos()->delete();
});
}
还有Photo Model (Photo.php)
protected static function boot() {
parent::boot();
static::deleting(function($photo) {
if ( File::exists(public_path($photo->path))) {
File::delete(public_path($photo->path));
}
}
});
}
将其视为链,当您删除Tour
时,如果删除Photos
文件正在删除,则会触发Photos
的删除。
这种方式有效,如果您删除Tour
或保留Tour
并仅删除Photo