作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在一对多多态关系中有三个表
┌─────────────────┐ ┌─────────────────┐ ┌──────────────────┐
│ users │ │ phones │ │ departments │
├─────────────────┤ ├─────────────────┤ ├──────────────────┤
| id | | id | | id |
| name | | name | | name |
└─────────────────┘ | phones_type | └──────────────────┘
| phones_id |
└─────────────────┘
手机型号:
public function phones()
{
return $this->morphTo();
}
用户模型:
public function phones()
{
return $this->morphMany('App\Phone', 'phones');
}
部门模型:
public function phones()
{
return $this->morphMany('App\Phone', 'phones');
}
现在我想更新电话号码,以便用户可以编辑/添加/删除号码..我无法一步搞定,所以我尝试先删除所有电话,然后添加新号码
我的代码:部门主管:
public function update(UpdateDepartment $request, Department $department)
{
$department->phones()->delete();
$department->name = $request['name'];
$department->save();
foreach ($request->phone as $value) {
$phone = new Phone;
$phone->name = $value;
$ department->phones()->save($phone);
}
}
更新部门.php :
public function rules()
{
return [
'name' => 'required|alpha_spaces|min:3|max:255|unique: department,name,'.$this-> department ->id,
'phone' => 'required|array|unique:phones,name,'
'phone.*' => 'required|distinct|unique:phones,name,',
];
}
我有两个问题:
1- 这是正确的做法吗?有没有办法一步同步更新的电话号码?
2- 如果是这样...如果用户只是将电话号码添加到现有号码,如何强制执行唯一规则忽略给定 ID?
最佳答案
1 - 你可以发送一些带有新电话号码的标识符 (id),这样你就会知道到底修改了什么电话号码,例如放一些 data-id="{{ $phone->id }}"
到 phone 字段并使用 javascript 构建请求以进行如下操作:
"phones":
{
"1"(your phone id):"+123456789",
"2":"+123654978",
}
然后像这样遍历请求数据:
public function update(UpdateDepartment $request, Department $department)
{
$department->name = $request['name'];
foreach ($request->phones as $id => $value) {
$department->phones->transform(function($item) use ($id, $value){
if($item->id == $id) {
$item->name = $value;
$item->save(); //if You using laravel 5 You need to savve each phone model separately
}
});
}
$department->push(); //if You using laravel 6.x, this will save model with all changed/created relations
}
但我建议将电话号码存储为 json
用于用户和部门的单独字段中,这样就可以简单地用请求中的新号码替换模型中的旧号码集而无需对数据库进行不必要的查询。
关于php - laravel - 更新一对多多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55846021/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!