【问题标题】:Why laravel 7 pivot with sync don't working?为什么 laravel 7 pivot with sync 不起作用?
【发布时间】:2022-01-11 08:37:09
【问题描述】:

这很好用。

    if ($request->link) {
        foreach($request->name as $key => $social){
            $stall->socials()->attach($social, ['value' => $request->link[$key] ?? null]);
        }
    }

但它不起作用。

    if ($request->link) {
        foreach($request->name as $key => $social){
            $stall->socials()->sync($social, ['value' => $request->link[$key] ?? null]);
        }
    }

Stall.php

public function socials()
{
    return $this->belongsToMany(Social::class)->withPivot('value');
}

问题是在更新过程中它根本不存储在数据库中。

【问题讨论】:

  • sync 不是这样工作的……第一个参数是要保持同步的 id 列表……laravel.com/docs/7.x/…(“同步关联”小节)……它解释了如何与其他字段同步
  • 如何用pivot保存?
  • 它在文档中告诉您如何执行此操作,您必须以特定方式构建一个数组以传递给sync 的第一个参数
  • 我将sync 替换为syncWithPivotValues,但出现错误Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::syncWithPivotValues()
  • 该方法在 Laravel 7.x 中不存在 ...您必须使用 sync ...这对您也不起作用,因为您需要为每个 id 设置不同的枢轴值同步

标签: php laravel laravel-7


【解决方案1】:

您需要以特定方式构建列表,以便在同步时在数据透视表上设置其他字段。这将是一个关联数组,其中键是 id,值是关联数组,其中键是字段,值是要在枢轴字段上设置的值。

您可以使用 Collection 以您需要的方式创建列表:

if ($request->link) {
    $stall->socials()->sync(collect($request->name)->mapWithKeys(
        fn ($value, $key) => [$value => ['value' => $request->link[$key] ?? null]]
    ));
}

如果您不使用 PHP 8,那么您可以调整为常规匿名函数而不是短箭头语法:

function ($value, $key) use ($request) { return [$value => ['value' => $request->link[$key] ?? null]]; }

Laravel 7.x Docs - Eloquent - Relationships - Inserting & Updating Related Models - Many To Many Relationships - Syncing Associationssync

Laravel 7.x Docs - Collections - Available MethodsmapWithKeys

【讨论】:

  • 我有一个错误i.stack.imgur.com/IOyAb.png
  • @MahmoudKhosravi 检查更新,忘记了use
  • 我再次收到此错误。 i.stack.imgur.com/P3Z7V.png
  • @MahmoudKhosravi 再次抱歉我的错误,已经晚了......它需要是一个关联数组(正如我在回答 blink blink 中所说的那样)
  • 我刚刚更新了答案以使用关联数组作为数据透视字段
猜你喜欢
  • 2018-01-01
  • 1970-01-01
  • 2020-03-16
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多