使用Laravel中的关系将动态数据保存到两个表中

时间:2017-11-15 10:29:02

标签: laravel laravel-eloquent

我有两张表StudentsHobbies。我在一个表单中列出了所有详细信息,但我想在提交时将详细信息保存到单独的表中。我怎样才能做到这一点?

我的学生模特

<?php

namespace App;

class Students extends Model {
protected $fillable = ['name', 'address'];

public function hobbies() {
    return $this->hasMany(Hobby::class);
}
}

爱好模型:

<?php

namespace App;

use App\Product;

class Hobby extends Model
{

protected $fillable = [
    'entertainment', 'sports'
    ];

public function hobby()
{
    return $this->belongsTo(Student::class);
}
}

控制器:

public function save(Request $request, Student $student)
{
    $students= new Student;
                $students->name= request('name');
                $students->address= request('address');
                $students->save();
    if($students->save())
    {
        $hobbies= [];
        $images = $request->file('hob_img');
        $hob_desc = $request->hob_desc;

        foreach ($request->hob_name as $key => $hobby) {
            $hob_img = '';
            {
                $hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
                $files[$key]->move(public_path('/assets/images/'), $hob_img);
            }
            $hobbies[] = [
                'hob_name' => $hobby,
                'hob_desc' => $hob_desc[$key],
                'hob_img' => $hob_img
            ];

        }     
        $hobbies[] = new Hobby;
                    $hobbies->hob_name = request('hob_name')[$key];
                    $hobbies->hob_desc= request('hob_desc')[$key];
                    $hobbies->hob_img = request($hob_img)[$key];
        $hobbies->save();

    }
}

但是我无法保存它。它说SQLSTATE[HY000]: General error: 1364 Field 'student_id' doesn't have a default value

1 个答案:

答案 0 :(得分:0)

尝试insert以保存许多记录:

public function save(Request $request, Student $student)
{
    $student= new Student;
    $student->name= request('name');
    $student->address= request('address');
    if($student->save())
    {
        $hobbies= [];
        $images = $request->file('hob_img');
        $hob_desc = $request->hob_desc;

        foreach ($request->hob_name as $key => $hobby) {
            $hob_img = '';

            $hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
            // $files i think it should be $images
            $files[$key]->move(public_path('/assets/images/'), $hob_img);

            $hobbies[] = [
                'hob_name' => $hobby,
                'hob_desc' => $hob_desc[$key],
                'hob_img' => $hob_img,
                'student_id'=> $student->id
            ];

        }
        Hobby::insert($hobbies); // useing Eloquent

        // Or you can use Query Builder 
        // DB::table('hobbies')->insert($hobbies);
    }
}