2016-10-28 2 views
0

내가 Laravel 5.3을 사용하고 있는데 나는 직장 내에서 사용자의 파일을 제거하기 위해 노력하고있어 :Laravel는 수집

public function handle() 
{ 
    //Remove all files from a message 
    $this->files->map(function($file) { 
     $path = $file->getPath(); 

     if(Storage::disk('s3')->exists($path)) 
     { 
      Storage::disk('s3')->delete($path); 
      if(!Storage::disk('s3')->exists($path)) 
      { 
       $attachment = File::find($file->id); 
       $attachment->delete(); 
      } 
     } 
    }); 
} 

을 그래서이 collections을위한 노력에 하나 개의 모델 인스턴스를 변환합니다. 하지만 모델 인스턴스 one을 전달하면 어떻게 작동합니까?

답변

1

먼저 컬렉션의 요소 또는 민간 방법을 같은 이동하는 웅변 모델은 다음과 같이 적용 할 알고리즘으로 :

private _removeFilesFromMessage($file) { 
    $path = $file->getPath(); 

    if(Storage::disk('s3')->exists($path)) 
    { 
     Storage::disk('s3')->delete($path); 
     if(!Storage::disk('s3')->exists($path)) 
     { 
      $attachment = File::find($file->id); 
      $attachment->delete(); 
     } 
    } 
} 

하는 것은 다음 수정 다음과 같은 핸들 메소드 :

public function handle() 
{ 
    if($this->files instanceof Illuminate\Database\Eloquent\Collection) { 
     //Remove all files from a message 
     $this->files->map($this->_removeFilesFromMessage($file)); 
    } else { 
     $this->_removeFilesFromMessage($this->files); 
    } 
} 

여기서 뭐하는거야? 우리는 $ this-> 파일 인스턴스가 Eloquent Collection인지 확인하고 있으며 조건이 true 인 경우 _removeFilesFromMessage를 map 메소드의 콜백으로 사용합니다. 그렇지 않으면 (나는 $ this-> 파일에 Eloquent Model 인스턴스가 있다고 가정하고 있습니다.) _removeFilesFromMessage 메서드가 호출되고 모델이 전달됩니다.

나는이 코드가 당신의 필요를위한 좋은 출발이라고 생각합니다. 이 질문의 제목으로

편집

완료의 문제에 대한 ... 당신이 질문 한 내용에서 부분적으로 다른 :

당신은 수집() 메소드 Laravel 컬렉션을 만들 수 있습니다

, Laravel 5.3 official doc

1

다른 방법으로도 만들 수 있습니다. 확인할 수 있습니다 경우 $this->filies

if($this->files instanceof Illuminate\Database\Eloquent\Collection) { 
    //so its a collection of files 
} else { 
    //its a one model instance 
//here you can do hack, 
    $this->files = collect([$this->files]); 
    //and code will works like a magic 
} 
+1

물론에 설명 된대로, 당신은 단지 확인하실 수 있습니다 경우 { $ this->'$ this-> files' '경우 (를 분명히 \ 데이터베이스 \ 웅변 \ 수집) instanceof를! ($ this-> 파일) files = collect ([$ this-> files ])); }' – mcklayin