首页 > 解决方案 > 总共有2个模型

问题描述

我有一个seances用 3 个字段命名的表(id、type_seance、price)

在此处输入图像描述

然后,我还有一个名为payments4 个字段的表(id、fk_type_seance、number_seance、total)

什么时候,我在我的表单中添加一个录音Payment

在此处输入图像描述

在此处输入图像描述

如果,我选择降神会的类型Theoretical(价格为 100 美元)并且我输入 2 类似降神会的数量,总金额为 200 美元。

我的控制器付款有问题,如何调整我的字段价格和 fk_type_seance ?检索总数?

$data['total'] = $request->price->fk_type_seance * $request->number_seance;

这是我的代码:

public function store(Request $request)
    {      

        $request->validate([
           'fk_type_seance' => 'required',
           'number_seance' => 'required',
           'total' => 'required'

         ]);

        $exists = Payment
                     ::where('fk_type_seance', $request->get('fk_type_seance'))
                     ->where('number_seance', $request->get('number_seance'))
                     ->where('total', $request->get('total'))
                     ->count();

       if (!$exists)
       {
            $data = $request->all(); 

            $data['total'] = $request->price->fk_type_seance * $request->number_seance;
            //Payment::create($request->all());
            Payment::create($data);
            return redirect()->route('payments.index')
                ->with('success', 'new data created successfully');
        }
        else
        {
            return redirect()->route('payments.index')
                ->with('error', 'doublon');

        }   

    }

现在,这是我的付款表格,我对总额有疑问。 在此处输入图像描述

编辑代码 jtwes

public function store(Request $request)
    {      

        $request->validate([
           'fk_type_seance' => 'required',
           'number_seance' => 'required',
           'total' => 'required'

         ]);

        $exists = Payment::where('fk_type_seance', $request->get('fk_type_seance'))->where('number_seance', $request->get('number_seance'))->where('total', $request->get('total'))->count();

       if (!$exists){
            $seance = Seance
                  ::where('id','=',$request->get('fk_type_seance'))
                  ->first();
            $seance = $request->all(); 
            if ($seance) $total = $seance->price * $request->number_seance;
            Payment::create($seance);
            return redirect()->route('payments.index')
                ->with('success', 'new data created successfully');
        }

        else{
            return redirect()->route('payments.index')
                ->with('error', 'doublon');

        }   

    }

标签: phplaravellaravel-5eloquentlaravel-5.8

解决方案


在计算之前,您必须先进行降神会......这样的事情:

$seance = Seance::where('id','=',$request->get('fk_type_seance))->first();
if ($seance) $total = $seance->price * $request->number_seance;

推荐阅读