【问题标题】:Laravel - Save additional column value to pivot tableLaravel - 将其他列值保存到数据透视表
【发布时间】:2020-06-11 16:29:52
【问题描述】:

我想将额外的布尔值保存到数据透视表的中间表中。 我有 belongstoMany 关系的模型。我想像这样保存数据透视表city_school

但是为所有学校保存了相同的 is_open 值。必须为每个 school_id 存储相关的 is_open 值。

city_id | school_id | is_open
   1          1         0
   1          2         1

我的模特:

City.php

public function schools()
{
    return $this->belongsToMany(School::class)->withPivot('is_open')->withTimestamps();
}

School.php

public function cities()
{
    return $this->belongsToMany(City::class)->withPivot('is_open')->withTimestamps();
}

View.blade.php

<div>LA<input type="hidden" name="school[]" value="1">
<input type="checkbox" name="is_open[1]">Open

<div>SF<input type="hidden" name="school[]" value="2">
<input type="checkbox" name="is_open[2]">Open

控制器

$school = $request['school'];
$data->schools()->attach($school, ['is_open' => $request->has('is_open')?1:0]);

【问题讨论】:

  • 在控制器中:$school是学校的id吗?确保它是。顺便说一句:一所学校怎么可能在一个以上的城市?不应该是一对多的关系吗?
  • $request-&gt;has('is_open') 总是true,因为它在技术上是一个数组。我认为您需要执行$request-&gt;has("is_open.{$school}") ? 1 : 0 才能获得特定学校的状态。实际上,如果 $request-&gt;input('school') 也是一个数组,你必须循环它以使 $request-&gt;has("is_open.{$school}") 工作......
  • @MaartenVeerman 我本来想对学校/城市说同样的话,但这是一个术语;我知道多个城市有同一个“学校”,但那是因为它有多个“校区”
  • @TimLewis 更改 $request-&gt;has("is_open.{$school}") ? 1 : 0 给出错误 Array to string conversion。 @Maarten,是的$school id 工作正常,城市/学校的逻辑是同一学校在不同城市的分支。
  • @deep 是的,请参阅我的第二个注释;我没有看到 $school 是一个 ID 数组。我想我有一个解决方案,让我试试吧。

标签: php laravel orm pivot-table


【解决方案1】:

由于$schools 是一个数组,您必须循环并构造所谓的“syncArray”:

$syncArray = [];
foreach ($request->input('schools') as $schoolId) {
  $syncArray[$schoolId] = [
    'is_open' => $request->has("is_open.{$schoolId}") ? 1 : 0
  ];
}

在上面的示例中,$syncArray 将包含一个 $schoolIds 数组,映射到一个“附加属性”数组,在本例中为 is_open

[1 => ["is_open" => 1], 2 => ["is_open" => 0]]

然后,您只需调用:

$data->schools()->syncWithoutDetaching($syncArray);

您的数据透视表中的所有记录都会更新以反映您已通过的内容。通常,您会调用sync(),但这会删除不在$syncArray() 中的任何内容,并且由于这只是更新一个属性,因此您不会想要这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2016-01-23
    • 2021-08-29
    • 2019-04-07
    • 2018-03-20
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多