【发布时间】:2019-08-22 23:57:21
【问题描述】:
我有Users和Operators,每个User只能有一个operator,但是Operator可以有很多用户
所以在 Operator 模型中我有:
public function profile() {
return $this->hasMany(User::class);
}
在用户模型中我有:
public function operator() {
return $this->hasOne(Operator::class);
}
所以我认为我的关系对吗?
现在,如果我有输入字段来管理运算符,并且我有多选框,因此我可以选择许多用户添加到该运算符,输入字段将类似于:
<select name="profiles[]" id="profiles" multiple="multiple" class="multiselect2 form-control">
@foreach($profiles as $key => $profile)
<option value="{{ $profile->id }}">{{ $profile->name }} {{ $profile->lastname }}</option>
@endforeach
</select>
在提交表单时,将发布所有选定的 $profiles 数组(这些是用户表中的用户)
对我来说有点棘手的是,当我创建新运算符并选择要附加到运算符的用户时,我不知道如何在没有数据透视表的情况下添加它们并同步,而且我不需要数据透视表表。
我有operators 表,该表应该包含操作员 ID 和托管用户 ID
+----+-------------+---------+
| id | operator_id | user_id |
+----+-------------+---------+
| 1 | 3 | 23 |
| 2 | 3 | 28 |
| 2 | 3 | 36 |
+----+-------------+---------+
那么如何在运营商表中添加(附加或连接)运营商和托管用户的用户 ID?
这是我当前的控制器代码
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
$user->operator()->attach(['operator_id' => $user->id, 'profile_id' => $request->profiles]);
【问题讨论】:
标签: php laravel eloquent many-to-many