1

我昨天开始使用 Laravel,ORM 似乎很强大。它有什么方法可以更新相关模型中的行吗?这是我尝试过的:

第 1 步:生成一个与数据库具有的确切结构的 JSON 对象。JSON 对象具有某些字段,这些字段是表示数据库中关系的子数组。

第 2 步:通过 POST 将 JSON 对象发送到 Laravel 进行处理,这里有点棘手:我可以先将 JSON 对象更改为数组

$array = (array) $JSONobject;

现在我需要更新,我希望这可以工作:

Product::update($JSONobject->id,$array);

但是由于数组有子数组,执行的更新SQL在表中找不到子数组列,而是去查找关联表。这可以做到吗?还是我也必须调用其他模型?

提前致谢!

4

1 回答 1

0

这是 Eloquent 无法为您处理的事情。您提供给该update()方法的数组应仅包含模型的列,在您的情况下Product。您可以尝试这样的事情来更新关系。这完全不在我的脑海中,并且从未经过测试。带上一粒盐。

$update = (array) $JSONobject;

$relations = [];

foreach ($update as $column => $value)
{
    // If the value is an array then this is actually a relation. Add it to the
    // relations array and remove it from the update array.
    if (is_array($value))
    {
        $relations[$column] = $value;

        unset($update[$column]);
    }
}

// Get the product from the database so we can then update it and update any of the
// the products relations.
$product = Product::find($update['id']);

$product->update($update);

foreach ($relations as $relation => $update)
{
    $product->{$relation}()->update($update);
}

上面的代码假定嵌套关系数组的键是关系的名称(模型中使用的方法名称)。您可能可以将其包装在Product模型上的方法中。然后就叫Product::updateRecursively($JSONobject);我很糟糕的名字,但你明白了。

这也可能不适用于更复杂的关系。对于多对多(甚至可能是一对多)之类的事情,您必须更进一步。

于 2013-04-11T12:37:28.743 回答