【问题标题】:laravel tables with relationship and insertion具有关系和插入的 laravel 表
【发布时间】:2020-08-30 22:02:57
【问题描述】:

我有 4 张桌子

  • 客户:客户数据。此表有很多(退款)
  • 退款:带有各种请求的数据。此表 belongsTo(Customers) AND belongsToMany(Services)
  • 服务:带有服务列表。此表属于ToMany(退款)
  • Refunds-Services:退款和服务的桥接表

我有一个必须在正确的表中插入数据的表单。

public function storeRefunds(RefundsPost $request){

    DB::beginTransaction();
        $customers = Customers::create($request->all());

        $refunds = $customers->refunds()->create([
            'date_ref' => request('date_ref'),
            'status_ref' => request('stato'),
        ]);

        $tipo = $request->input('tipo', []);
        $importo = $request->input('importo', []);

        $refunds = Refunds::create($request->all());
        for ($i=0; $i < count($tipo); $i++) {
            if ($tipo[$i] != '') {

                $refunds->services()->attach($tipo[$i], [
                'services_id' => $tipo[$i],
                'services_amount' => $importo[$i]
                ]);
            }
        }

        return redirect("/");

}

使用此代码,我可以将所有数据插入正确的表中,但在 Refunds 表中找不到 ID 连接。 Refunds 表中创建了两个不同的 ID。在 Refunds 表中创建的第二个 ID 未连接到任何客户 (0),但连接到选择的服务列表。 我能怎么做? 谢谢

【问题讨论】:

  • 只需删除$refunds = Refunds::create($request-&gt;all());。再次运行代码并检查映射。

标签: laravel eloquent relationship


【解决方案1】:

您需要调试代码。首先Refund 在这一行创建$refunds = $customers-&gt;refunds()-&gt;create,它属于Customer,第二个Refund 在此处创建:$refunds = Refunds::create($request-&gt;all());,它与任何Customer 无关,但与Service 相关(你可以这在for 循环中)。顺便说一句,您的tipo 输入不是多个(如果您希望它可以是多个值,它应该与[] 一起使用)并且for 循环在这种情况下毫无意义。

删除Refunds::create方法之一,将您的数据带到预期视图并使用createMany()方法。

Laravel 文档中的更多信息:https://laravel.com/docs/7.x/eloquent-relationships#the-create-method

【讨论】:

  • 我的提示是多个,因为服务可以在一个退款请求中添加
  • 所有数据都正确存储在所有表中,但唯一的错误是当它将服务与请求相关联时,它会创建一个未连接到任何客户的新请求 ID
  • 通过一次提交,我在退款表中创建了 2 个 ID,第一个 ID 与客户正确连接,但第二个 ID 没有用,它连接到所选的各种服务。我的意思是选择的服务连接到错误的无用的第二个在退款中生成 id
  • 也许我不能使用 Eloquent 关系来做到这一点,我必须手动传递 id?
猜你喜欢
  • 2018-10-09
  • 2018-06-25
  • 1970-01-01
  • 2013-06-06
  • 2010-10-29
  • 2013-12-31
  • 2016-10-05
  • 2018-03-22
  • 1970-01-01
相关资源
最近更新 更多