简体   繁体   English

如何在Laravel中存储文件和模型之间的关系?

[英]How to store a relationship between a file and a model in Laravel?

I have the below controller. 我有下面的控制器。 I need to save the Document Model with the Employee_id relationship. 我需要使用Employee_id关系保存文档模型。 I have the relationship set correctly but I a, having SQL error where it says employee_id cannot be null, foreign key violation. 我的关系设置正确,但是我有一个SQL错误,该错误指出employee_id不能为null,违反外键。

So I think I have to find a way for the controller to recognise the currently loaded id for the employee profile view then save the document model. 因此,我认为我必须找到一种方法,使控制器识别员工资料视图的当前加载的ID,然后保存文档模型。 The upload works fine. 上载正常。 It's writing to the DB part that I need help. 它正在写给数据库部分,我需要帮助。 Code here.... 在这里编码...。

public function createdocument(Request $request, Employee $id)
{


    $file = $request->file('file');
    $allowedFileTypes = config('app.allowedFileTypes');
    $maxFileSize = config('app.maxFileSize');
    $rules = [
        'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
    ];
    $this->validate($request, $rules);


    $time = time();  
    $filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename 
     $destinationPath = config('app.fileDestinationPath').'/'.$filename;
        $uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
        if($uploaded){

            $employee = Employee::find($id); 

            EmpDocuments::create([
                'employee_id' => $employee,
                'name' => $filename
            ]);
        }    
        return redirect('employees');
}

If you print_r($employee), it should return object, that's why its giving null exception. 如果您使用print_r($ employee),它应该返回object,这就是为什么它给出null异常的原因。

You have to get ID of employee: 您必须获得员工ID:

EmpDocuments::create([
    'employee_id' => $employee->id,
    'name' => $filename
]);

Also, your saying that your sending $id of employee to model, but instead, it expects Employee object. 同样,您说的是您发送要建模的employee的$ id,但相反,它期望Employee对象。 Not id. 不是id。

So you have to change 所以你必须改变

createdocument(Request $request, Employee $id)

to

createdocument(Request $request, $id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM