Laravel附加问题

时间:2016-06-30 09:25:41

标签: laravel pivot

我要将具有各种数据透视值的特定present项目附加到单个order。我正在寻找类似的东西:

$order->presents()->attach(1,[
    ['price' => '2400, 'qty' => 2],
    ['price => '1000, 'qty' => 4]
  ]);

当然它不是有效的代码。我可以逐个附加项目:

$order->presents()->attach(1,['price' => '2400, 'qty' => 2]);

$order->presents()->attach(1,['price => '1000, 'qty' => 4]);

但我认为应该有更好的方法,任何人都可以告诉我如何做一堆附加?

2 个答案:

答案 0 :(得分:0)

看看documentation我可以看到你几乎得到了解决方案。

参考文档,您应该使用像array(id => [values])这样的数组。在你的情况下:

$order->presents()->attach([
    1 => [
        'price' => 2400,
        'qty' => 2
    ],
    ....
]);

此代码尚未经过测试。

修改

当您检查Laravel框架的深层地牢中的attach()函数时,可以看到它也接受模型,集合或整数。当你进一步观察时,你可以看到它(也许)也接受一系列ID。

/**
 * Attach a model to the parent.
 *
 * @param  mixed  $id
 * @param  array  $attributes
 * @param  bool   $touch
 * @return void
 */
public function attach($id, array $attributes = [], $touch = true)
{
    if ($id instanceof Model) {
        $id = $id->getKey();
    }

    if ($id instanceof Collection) {
        $id = $id->modelKeys();
    }

    $query = $this->newPivotStatement();

    $query->insert($this->createAttachRecords((array) $id, $attributes));

    if ($touch) {
        $this->touchIfTouching();
    }
}

不知道它是否有效,但请尝试:

$order->presents()->attach([1, 1], [[
            'price' => 2400,
            'qty' => 2
        ], [
            'price' => 1337,
            'qty' => 420
        ]
    ]
]);

答案 1 :(得分:0)

您可以这样做:

$order->presents()->attach([
1 => ['count' => 3, 'price' => '2400, 'qty' => 2],
2 => ['count' => 4, 'price' => '2400, 'qty' => 2]
]);