Сохранение массива данных динамических полей в БД с использованием отношения oneToMany - PullRequest
0 голосов
/ 22 апреля 2019

Я пытался сохранить данные, поступающие из динамически сгенерированных полей, в виде массива. У меня есть отношения oneToMany для таблицы клиентов.

enter image description here

Я пытался пройтись по каждому полю, но я не смог его достичь, пожалуйста, исправьте меня, если я ошибаюсь.

public function store(Request $request)
{
    $res = $request->all();
    $res['address'] = implode(' ', array_values($request->address));
    $customer = Customer::create($res);
    if ($res) {
        $customerData = [];
        foreach ($request->department_name as $key => $n) {
            $customerData = array(
                'department_name' => $request->department_name[$key],
                'person_name' => $request->person_name[$key],
                'person_number' => $request->person_number[$key],
                'person_email' => $request->person_email[$key],
                'notification_flag' => !isset($request->notification_flag[$key]) ? 0 : $request->notification_flag[$key] === "on" ? 1 : 0,
                'custinvoice_noti' => !isset($request->outstanding[$key]) ? 0 : $request->outstanding[$key] === "on" ? 1 : 0,
                'invoice_noti' => !isset($request->invoice[$key]) ? 0 : $request->invoice[$key] === "on" ? 1 : 0,
            );

            $deptModel[] = new Department($customerData);
            $customer->department()->saveMany($deptModel);
        }
    }
    return redirect('admin/customers');
}

Модель клиента и модель отдела имеют следующие отношения.

class Customer extends Model
{
protected $fillable = ['owner_name', 'address', 'country', 'state', 'city', 'pincode', 'number', 'correspondance_check'];

public function department()
{
    return $this->hasMany('App\Department');
}
}

Модель отдела.

class Department extends Model
{
protected $fillable = ['customer_id', 'department_name', 'person_name', 'person_number', 'person_email', 'notification_flag', 'notification_type'];

public function customer()
{
    return $this->belongsTo('App\Customer');
}
}

enter image description here

Ответы [ 2 ]

0 голосов
/ 23 апреля 2019

хранилище общедоступных функций (Запрос $ запрос) {$ customer = new Customer ();

    $customer->owner_name = $request['owner_name'];
    $customer->country = $request['country'];
    $customer->state = $request['state'];
    $customer->city = $request['city'];
    $customer->pincode = $request['pincode'];
    $customer->number = $request['number'];
    $customer->correspondance_check = $request['correspondance_check'];
    $res = $customer->save();
    $cus = Customer::where(['id'=> $res->id])->firstOrFail();
    $dep = new Department();
    $dep->customer()->associate($cus);
    $dep->save();

    return redirect('admin/customers');
    // return response()->json($customerData);
}

Customer model and  Department model have the following relationship.

class Customer extends Model
{

protected $fillable = ['owner_name', 'address', 'country', 'state', 'city', 'pincode', 'number', 'correspondance_check'];

public function department()
{
    return $this->hasMany('App\Department');
}

}

//Department Model.

class Department extends Model
{
protected $fillable = ['customer_id', 'department_name', 'person_name', 'person_number', 'person_email', 'notification_flag', 'notification_type'];

public function customer()
{
    return $this->belongsTo('App\Customer');
}
}
0 голосов
/ 23 апреля 2019

Ваш код выглядит таким грязным. Вы должны попытаться использовать insert oneToMany от laravel eloquent. Следуйте этой проблеме: Laravel сохранить отношения один ко многим . В любом случае, вы должны использовать formrequest для повторного использования вашего кода и более стандартным.

...