douao1926 2018-08-31 09:52 采纳率: 0%
浏览 53
已采纳

在雄辩的多对多插入中添加多个额外属性数组会给我带来错误

I am new to Laravel framework. To be exact, I'm using Laravel 5.6 now. Recently I have some problem with insertion of many-to-many relation with an array of extra attributes.

Here is my script:

$data = [
      "produk_id" => [
        0 => 17,
        1 => 7,
        2 => 2,
      ],
      "tarif" => [
        29290,
        119395,
        89873,
      ],
      "qty" => [
        0 => 4,
        1 => 6,
        2 => 13,
      ],
    ];

Transaksi::find(1)->produk()->attach($data['produk_id'], ['tarif'=>$data['tarif']]);

It gives me this error:

got some exception, but... the query seems to be true. hmmm...

It is strange that the query produced seems to be true. But warn by some exception.

So, i then change the strategy to map the tarif array that suit to the Eloquent documentation like this:

$data_tarif = array_map(function ($item) {
        return ['tarif' => $item];
    }, $data['tarif']);

And then pass it to second parameter of attach as extra attributes:

Transaksi::find(1)->produk()->attach($data['produk_id'], $data_tarif);

But it still gives me an exception, even so far from my expectation:

So far from expectation query

Am I wrong to use that attach method with multiple arrays of an extra attribute? Since I've tried with a simple array or Laravel documentation, but they seem not work well. what should I do to fix them?

Some attachment to help:
This is my Transaksi model and Produk model

class Transaksi extends Model
{
   protected $table = 'transaksi';

   public function user()
   {
      return $this->belongsTo(User::class, 'user_id');

   public function customer()
   {
      return $this->belongsTo(Customer::class, 'customer_id');
   }

   public function produk()
   {
      return $this->belongsToMany(Produk::class, 'detail_transaksi');
   }
}


class Produk extends Model
{
  protected $table = 'produk';

  public function transaksi() 
  {
      return $this->belongsToMany(Transaksi::class, 'detail_transaksi');
  }
}
  • 写回答

1条回答 默认 最新

  • duanchen1937 2018-08-31 10:59
    关注

    try this:

    $attachArray = array();
    foreach ($data['produk_id'] as $index => $id) {
        $attachArray[$id] = ['tarif' => $data['tarif'][$index]];
    }
    Transaksi::find(1)->produk()->attach($attachArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置