douju7765 2019-04-22 15:59
浏览 45

使用oneToMany关系将动态字段数据数组保存到DB

I have been trying to save the data coming from the dynamically generated fields in the form of an array. I have a oneToMany relationship for the customer table.

enter image description here

I have tried to loop through each field but I am unable to achieve it, please correct me if I am wrong.

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');
}

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');
}
}

enter image description here

  • 写回答

2条回答 默认 最新

  • doutan3371 2019-04-23 08:57
    关注

    Your code look so messy. You should try to use insert oneToMany by laravel eloquent. Follow this issue:Laravel save one to many relationship. Anyways, you should use formrequest to reuse your code and more standard.

    评论

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab