在 Laravel 中同步一对多关系

2022-08-30 11:10:57

如果我有一个多对多的关系,那么用它的方法更新关系是非常容易的。sync

但是,我将使用什么来同步一对多关系呢?

  • 桌子:postsid, name
  • 桌子:linksid, name, post_id

在这里,每个都可以有多个s。PostLink

我想根据输入的链接集合(例如,从 CRUD 表单中添加、删除和修改链接)同步与数据库中特定帖子关联的链接。

应删除数据库中不存在于我的输入集合中的链接。应更新数据库和输入中存在的链接以反映输入,并且应将仅存在于我的输入中的链接作为数据库中的新记录添加。

总结所需行为:

  • inputArray = true / db = false ---CREATE
  • inputArray = false / db = true ---DELETE
  • inputArray = true / db = true ----UPDATE

答案 1

不幸的是,没有一对多关系的方法。自己动手很简单。至少如果您没有任何外键引用。因为这样您就可以简单地删除行并再次插入它们。synclinks

$links = array(
    new Link(),
    new Link()
);

$post->links()->delete();
$post->links()->saveMany($links);

如果您确实需要更新现有的(无论出于何种原因),则需要完全按照您在问题中描述的操作。


答案 2

删除和重新添加相关实体的问题在于,它将破坏您可能对这些子实体具有的任何外键约束。

更好的解决方案是修改Laravel的关系以包含一种方法:HasManysync

<?php

namespace App\Model\Relations;

use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * @link https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Relations/HasMany.php
 */
class HasManySyncable extends HasMany
{
    public function sync($data, $deleting = true)
    {
        $changes = [
            'created' => [], 'deleted' => [], 'updated' => [],
        ];

        $relatedKeyName = $this->related->getKeyName();

        // First we need to attach any of the associated models that are not currently
        // in the child entity table. We'll spin through the given IDs, checking to see
        // if they exist in the array of current ones, and if not we will insert.
        $current = $this->newQuery()->pluck(
            $relatedKeyName
        )->all();
    
        // Separate the submitted data into "update" and "new"
        $updateRows = [];
        $newRows = [];
        foreach ($data as $row) {
            // We determine "updateable" rows as those whose $relatedKeyName (usually 'id') is set, not empty, and
            // match a related row in the database.
            if (isset($row[$relatedKeyName]) && !empty($row[$relatedKeyName]) && in_array($row[$relatedKeyName], $current)) {
                $id = $row[$relatedKeyName];
                $updateRows[$id] = $row;
            } else {
                $newRows[] = $row;
            }
        }

        // Next, we'll determine the rows in the database that aren't in the "update" list.
        // These rows will be scheduled for deletion.  Again, we determine based on the relatedKeyName (typically 'id').
        $updateIds = array_keys($updateRows);
        $deleteIds = [];
        foreach ($current as $currentId) {
            if (!in_array($currentId, $updateIds)) {
                $deleteIds[] = $currentId;
            }
        }

        // Delete any non-matching rows
        if ($deleting && count($deleteIds) > 0) {
            $this->getRelated()->destroy($deleteIds);    
        }

        $changes['deleted'] = $this->castKeys($deleteIds);

        // Update the updatable rows
        foreach ($updateRows as $id => $row) {
            $this->getRelated()->where($relatedKeyName, $id)
                 ->update($row);
        }
        
        $changes['updated'] = $this->castKeys($updateIds);

        // Insert the new rows
        $newIds = [];
        foreach ($newRows as $row) {
            $newModel = $this->create($row);
            $newIds[] = $newModel->$relatedKeyName;
        }

        $changes['created'] = $this->castKeys($newIds);

        return $changes;
    }


    /**
     * Cast the given keys to integers if they are numeric and string otherwise.
     *
     * @param  array  $keys
     * @return array
     */
    protected function castKeys(array $keys)
    {
        return (array) array_map(function ($v) {
            return $this->castKey($v);
        }, $keys);
    }
    
    /**
     * Cast the given key to an integer if it is numeric.
     *
     * @param  mixed  $key
     * @return mixed
     */
    protected function castKey($key)
    {
        return is_numeric($key) ? (int) $key : (string) $key;
    }
}

您可以重写 Eloquent 的类以代替标准关系使用:ModelHasManySyncableHasMany

<?php

namespace App\Model;

use App\Model\Relations\HasManySyncable;
use Illuminate\Database\Eloquent\Model;

abstract class MyBaseModel extends Model
{
    /**
     * Overrides the default Eloquent hasMany relationship to return a HasManySyncable.
     *
     * {@inheritDoc}
     * @return \App\Model\Relations\HasManySyncable
     */
    public function hasMany($related, $foreignKey = null, $localKey = null)
    {
        $instance = $this->newRelatedInstance($related);

        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $localKey = $localKey ?: $this->getKeyName();

        return new HasManySyncable(
            $instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey
        );
    }

假设您的模型扩展并具有关系,您可以执行如下操作:PostMyBaseModellinks()hasMany

$post->links()->sync([
    [
        'id' => 21,
        'name' => "LinkedIn profile"
    ],
    [
        'id' => null,
        'label' => "Personal website"
    ]
]);

将更新此多维数组中具有与子实体表 () 匹配的任何记录。表中此数组中不存在的记录将被删除。数组中不存在于表中的记录(具有不匹配的 或 null 的 )将被视为“新”记录,并将插入到数据库中。idlinksidid


推荐