简体   繁体   中英

Laravel 5.2 save data to m:n table

I have problem with saving data to m:n table layout in laravel 5. I have table appliances and table documentations, where pivot table is documentation_appliance.

Models are:

   class Appliances extends Model
    {    
        public function documentations()
        {
            return $this->belongsToMany('documentations');
        }

    }

and

class Documentation extends Model
{
public function appliances()
{
    return $this->belongsToMany('appliances');
}
}

Now I try to save data to table in my Controller

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required|max:255',
        'file_name' => 'required',
    ]);

    if($request->hasFile('file_name') ) {
        $fname = $request->file('file_name')->getClientOriginalName();
        $request->file('file_name')->move(
            base_path() . '/public/files/documentation/', $fname
        );
    }

    $document = new Documentation();
    $document->name = $request->name;
    $document->filename = $fname;


    if($document->save()) {
        $doc_ids = $request->documentation_appliance;
        $document->appliances()->sync($doc_ids);
    }

    return view('backend.documentation.index', [
        'documentations' => $this->documents->getDocuments(),
    ]);
}

Data to table documents are saved corectly, image is stored, but I have problem with saving data to pivot table. Screen displays me this error:

FatalErrorException in compiled.php line 10191:

Class 'appliances' not found

in compiled.php line 10191

nothing more, I guess I have bad use of class somewhere or am I doing bad something else? Thanks everyone for help.

根据https://laravel.com/docs/5.2/eloquent-relationships#many-to-many,您的表名称必须是Appliance_documentation而非documentation_appliance。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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