如何在Laravel中从一个带有关系的JSON对象更新和创建新行?


How can you update and create a new row in Laravel from a JSON object with relationships?

我昨天开始使用Laravel, ORM似乎很强大。它有任何方式更新行在相关的模型?这是我尝试过的:

步骤1:生成与数据库结构完全相同的JSON对象。JSON对象有一些字段,这些字段是子数组,表示数据库中的关系。

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

$array = (array) $JSONobject;

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

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

但是由于数组有子数组,执行update SQL时无法在表中找到子数组列,而应该查找关联的表。这能做到吗?还是我也要打电话给其他型号?

提前感谢!

这是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);吧。我不太会记名字,不过你懂的。

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