gpt4 book ai didi

laravel - Eloquent :如何在不删除任何内容的情况下同步一对多关系(FK 可为空)?

转载 作者:行者123 更新时间:2023-12-04 14:22:20 27 4
gpt4 key购买 nike

一个分支机构可能有零个(*) 或只有一个假期计划。假期计划可以“链接”(附加)到零个或多个分支。

(*) 这很重要:它是一个外键,可能是null

enter image description here

模型

这是我的 Branch 模型:

class Branch extends Model
{
protected $table = 'branch';
protected $fillable = ['name', 'holiday_plan_id'];
public $timestamps = false;

public function holidayPlan()
{
return $this->hasOne('App\HolidayPlan', 'id', 'holiday_plan_id');
}
}

这是我的 HolidayPlan 模型:

class HolidayPlan extends Model
{
protected $table = 'holiday_plan';
protected $fillable = ['name'];
public $timestamps = false;

public function branches()
{
return $this->hasMany('App\Branch', 'holiday_plan_id', 'id');
}
}

查看

现在我想将假期计划链接/取消链接到不同的分支机构

$branches = Branch::all();
$plan = HolidayPlan::find(1);

@foreach($branches as $branch)
<label>
<input type="checkbox" name="branch[]"
value="{{ $branch->id }}"{{ ($branch->holiday_plan_id == $plan->id) ? ' checked' : '' }}>
{{ $branch->name }}
</label>
@endforeach

Controller

public function linkBranches($planId, Request $request) // post
{
$plan = HolidayPlan::where('id', $planId)->first();
$branches = Branch::findMany($request->input('branch'));
//
$this->solution1($plan, $branches); // see next
//
return redirect()->back();
}

可能的解决方案(不工作)

private function solution1(HolidayPlan $plan, $branches)
{
$plan->branches()->sync($branches); // Not working because this function is for Many-to-Many relations
}

private function solution2(HolidayPlan $plan, $branches)
{
$plan->branches()->delete(); // This will delete my branches, which is not what I want to do, of course
$plan->branches()->saveMany($branches);
}

private function solution3(HolidayPlan $plan, $branches)
{
foreach($plan->branches as $branch) {
$branch->holiday_plan_id = null;
$branch->save();
}
$plan->branches()->saveMany($branches); // Not working; I don't know why: strange behavior. Maybe because of locks; I'm not sure. One time it detaches all branches, and only next time it attaches them again.
}

最后

实际上,原始 SQL 是:

UPDATE branch SET holiday_plan_id = NULL WHERE holiday_plan_id = 1;
UPDATE branch SET holiday_plan_id = 1 WHERE branch.id IN (2, 5, 7)/* for example */;

但是如何使用 Eloquent 函数和关系(没有原始 sql)来做到这一点?


编辑

我已经编辑了我的 Branch 模型关系,但是 solution3 仍然不起作用(当我尝试添加一个已经存在的 holiday_plan_id ,它不添加它 = 它变为空):

public function holidayPlan()
{
return $this->belongsTo('App\HolidayPlan', 'holiday_plan_id');
}

最佳答案

临时解决方案:

public function solution4(HolidayPlan $plan, $inputBranches)
{
$oldLinks = $plan->branches;
$plan->branches()->saveMany($inputBranches);
foreach ($oldLinks as $oldLink) {
if (! $inputBranches->contains($oldLink)) {
$oldLink->holiday_plan_id = null;
$oldLink->save();
}
}
}

关于laravel - Eloquent :如何在不删除任何内容的情况下同步一对多关系(FK 可为空)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52864540/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com