在Laravel中同步一对多关系

问题描述 投票:14回答:3

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

但是我会用什么来同步一对多的关系呢?

  • postsid, name
  • linksid, name, post_id

在这里,每个Post可以有多个Links。

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

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

总结所需的行为:

  • inputArray = true / db = false --- CREATE
  • inputArray = false / db = true --- DELETE
  • inputArray = true / db = true ----更新
php laravel eloquent one-to-many crud
3个回答
14
投票

不幸的是,没有用于一对多关系的sync方法。自己做这件事非常简单。至少如果你没有任何外键引用links。因为那时你可以简单地删除行并再次插入它们。

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

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

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


3
投票

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

更好的解决方案是修改Laravel的HasMany关系以包含sync方法:

<?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的Model类以使用HasManySyncable而不是标准的HasMany关系:

<?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
        );
    }

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

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

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


0
投票

我确实喜欢这个,它针对最小查询和最小更新进行了优化:

首先,将链接ID与数组同步:$linkIds和post模型在其自己的变量中:$post

Link::where('post_id','=',$post->id)->whereNotIn('id',$linkIds)//only remove unmatching
    ->update(['post_id'=>null]);
if($linkIds){//If links are empty the second query is useless
    Link::whereRaw('(post_id is null OR post_id<>'.$post->id.')')//Don't update already matching, I am using Raw to avoid a nested or, you can use nested OR
        ->whereIn('id',$linkIds)->update(['post_id'=>$post->id]);
}
© www.soinside.com 2019 - 2024. All rights reserved.