[英]Laravel ManyToMany relationships and attach without pivot table from input field array
我有用户和操作员,每个用户只能有一个操作员,但操作员可以有很多用户
所以在运营商模型中我有:
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>
在表单提交,将发布所有选定的$配置文件的数组(这些是用户表中的用户)
对我来说有点棘手的是当我创建新的运算符并选择要附加到运算符的用户时,我不知道如何添加它们并在没有数据透视表的情况下同步,我根本不需要数据透视表为了这。
我有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]);
只需使用eloquent进行连接即可。
DB::select("SELECT * FROM Users u
INNER JOIN operators o dp ON u.id = o.user_id;");
只需确保为每个需要连接的表执行连接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.