【问题标题】:Updating Middle Table Laravel Relationship更新中间表 Laravel 关系
【发布时间】:2018-06-02 06:17:38
【问题描述】:

我有一个包含'Officiant_id''awards_id' 的表

当用户编辑他们的个人资料时,它会在复选框中显示所有可用的个人资料并自动检查该表格上的个人资料。

虽然,现在是更新的时候了,假设用户取消选择了一个,我如何更新表格以删除它,或者如果他们检查了一个新的将新的添加到表格中。

@if(!empty($officiant - > useraward))
@foreach($officiant - > useraward as $arr)
@php $removeId[] = $arr - > id @endphp {
    {
        Form::checkbox('awards[]', $arr - > id, true, ['class' => ''])
    }
} {
    {
        $arr - > name
    }
} {
    !!'<br>'!!
}
@endforeach
@endif

@php
$offaward = Info::officiantAwards();
foreach($removeId as $key) {
    unset($offaward[$key]);
}

@endphp

@foreach($offaward as $k => $v) {
    {
        Form::checkbox('awards[]', $k, false)
    }
} {
    {
        $v
    }
} {
    !!'<br>'!!
}
@endforeach

if (!empty($request - > awards)) {
    foreach($request - > awards as $i => $k) {
        $awards[] = $request - > $k;
    }
}

【问题讨论】:

    标签: php mysql laravel laravel-5 laravel-4


    【解决方案1】:

    以数组的形式获取所有奖项并在您的$officiant 上调用sync() 方法。根据documentation/同步关联

    你也可以使用sync方法来构造many-to-many 协会。 sync 方法接受一个 ID 数组放置在 中间表。任何不在给定数组中的 ID 都将是 从中间表中删除。所以,在这个操作之后 完整,只有给定数组中的 ID 将存在于 中间表:

    所以在你调用update()save() 之后,

    //get all award ids
    $awards = $request->get('awards');
    
    //save or update officient action
    
    //updating relation
    $officiant->awards()->sync($awards);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多