我有组和组成员,一个表用于组,其中我只存储组名,第二个表是组成员,其中我有user_id,group_id字段。
我正在使用邮递员创建API,我想插入小组成员的详细信息,如下所示:
"group_members": [1,3]
我的身体要求是:
{
"name": "Steve", // name is group name
"group_members": [1,3] // [1,3] here 1 and 3 is user_id
}
我要针对[group_id]将[1,3]存储到user_id字段的group_members表中,如果存在[1,3],则应在user_id字段中输入两个条目 我还附上了桌子的屏幕截图:
我的控制器:
DB::beginTransaction();
try{
$request->request->add(['created_by' => Auth::user()->id]);
$group = $this->group->create($request->only($this->group->getModel()->fillable));
$request->request->add(['group_id' => $group->id]);
$this->groupMembers->create($request->only($this->groupMembers->getModel()->fillable));
DB::commit();
return response([
'status' => true,
'message' => 'Group added',
], 200);
} catch(\Exception $ex) {
DB::rollback();
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $ex->getMessage(),
], 500);
}
我如何将这个数组值存储到数据库中,您的帮助将不胜感激?https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy?view=powershell-6
try {
$group = $this->group->find($request->input('id'));
$request->request->add(['updated_by' => Auth::user()->id]);
$group->fill($request->all())->save();
return response(['status' => true, 'message' => 'Group updated'], 500);
} catch (\Exception $ex) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $ex->getMessage()], 500);
}
public function updateGroup(Request $request)
{
$validator = UserValidations::validateGroup($request->all());
if($validator->fails()) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
}
try {
$group = $this->group->find($request->input('id'));
$request->request->add(['updated_by' => Auth::user()->id]);
$group->fill($request->all())->save();
return response(['status' => true, 'message' => 'Group updated'], 500);
} catch (\Exception $ex) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $ex->getMessage()], 500);
}
}
答案 0 :(得分:0)
更改这两行
$request->request->add(['group_id' => $group->id]);
$this->groupMembers->create($request->only($this->groupMembers->getModel()->fillable));
收件人
$user_ids = $request->get('group_members');
foreach($user_ids as $user_id){
$this->groupMembers->create(['group_id' => $group->id, 'user_id'=>$user_id]);
}
希望这可以解决您的问题。
答案 1 :(得分:0)
使用attach和many to many关系来做。
Group.php
&
User.php
let urls = URL(string: "itms-apps://itunes.apple.com/in/app/brother-iprint-label/id523047493?mt=8")
if UIApplication.shared.canOpenURL(urls!) {
UIApplication.shared.open(urls!, options: [:], completionHandler: nil)
}
现在,您只需执行以下操作即可按其ID将成员添加到组中:
class Group extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'group_members');
}
}
如果您要从组中删除一个或多个成员,则同样如此:
class User extends Model
{
public function groups()
{
return $this->belongsToMany('App\Group', 'group_members');
}
}