2017-07-06 73 views
1

我有這樣的關係模型User複製另一個模型文件附件十月CMS

public $attachMany = [ 
    'logos' => ['System\Models\File', 'delete' => true] 
]; 

public $hasMany = [ 
    'jobs' => ['Acme\Plugin\Models\Job'] 
]; 

我也有在Job模型如下關係:

public $attachOne = [ 
    'logo' => ['System\Models\File', 'delete' => true] 
]; 

所以,一User可以附加大量徽標,當用戶創建Job時,他們可以附加一個徽標。

User創建Job並附加一個標誌吧,我需要他們能夠選擇連接已經連接到User的標誌之一,但我不希望它是實際的關係(即:不是多對多的關係),而是完全重複的File,以便如果用戶稍後決定在以後的日期刪除他們的一些徽標,它不會影響附加的徽標工作。

我理論上已經解決了這個問題,並回答了我自己的問題,但它非常混亂,我不禁想到可能有一個更簡單的方法。

// Get the File model 
    $chosenLogo = \System\Models\File::find(1); 

    // Save the contents of the file to local storage 
    Storage::disk('local')->put('tempLogos/' . $chosenLogo->disk_name, $chosenLogo->getContents()); 

    // Get the job 
    $job = \Acme\Plugin\Models\Job::find(34); 

    // Create a new File and specify path for data 
    $file = new \System\Models\File; 
    $file->data = base_path('storage/app/tempLogos/' . $chosenLogo->disk_name); 

    // Save file then attach logo to job 
    $file->save(); 
    $job->logo()->add($file); 

它的工作原理,但它是一個很大的混亂。有更容易的方法嗎?

+0

你的問題解決了我的問題,「如何複製文件模型」。對不起,沒有幫助你的問題,但感謝你的代碼如何做到這一點。 –

回答

0

也許解決方案可以與行爲。擴展\System\Models\File類與clone()copy()方法,用這樣的:

public static function clone(){ 
    Storage::disk('local')->put('temp/' . $this->disk_name, $this->getContents()); 
    // Create a new File and specify path for data 
    $file = new \System\Models\File; 
    $file->data = base_path('storage/app/temp/' . $this->disk_name); 

    // Save file then attach logo to job 
    $file->save(); 

    return $file; 
} 
0

有沒有更簡單的方法,您的解決方案是存儲在物理複製磁盤上已經存儲的文件和記錄一個新\System\Models\File的正確方法在這個副本的數據庫中。

相關問題