简体   繁体   English

如何插入多个ID并保存在数据库中

[英]How to insert multi IDs and save in database

I'm using Laravel 7 and trying to make a automation system.我正在使用 Laravel 7 并尝试制作自动化系统。
For send Letters, I have to be able to choose a few receivers.对于发送信件,我必须能够选择几个接收者。

Here is Letter table:这是字母表: 在此处输入图像描述

As you can see, I have recieve_id .如您所见,我有recieve_id
I can get IDs, but I don't know how to save IDs in my database.我可以获得 ID,但我不知道如何将 ID 保存在我的数据库中。

This is my select:这是我的 select:

<select class="col-12 border mt-2 pt-2" multiple="multiple" name="recieve_id[]">
  @foreach($users as $user)
    <option value="{{ $user->id }}">{{ $user->name }}</option>
  @endforeach
</select>

This is my Controller:这是我的 Controller:

Letter::create([
  'indicator_id' => $request['indicator_id'],
  'sender_id' => auth()->user()->id,
  'recieve_id' => $request['recieve_id'],
  'title' => $request['title'],
  'image' => 'default.png',
  'description' => $request['description'],
  'date' => $request['date'],
  'text' => $request['text'],
]);
return redirect(route('Letter.index'));

Edit:编辑:

Here is Table structure:这是表结构: 在此处输入图像描述

Edit 2:编辑2:

Here is my destory function for letters: Destory Function这是我的 destory function 字母: Destory Function

If I am understanding your question right, the code you have written in the controller is not working well or not creating database entry.如果我对您的问题的理解正确,那么您在 controller 中编写的代码运行不正常或没有创建数据库条目。 Is it right?这样对吗?

If yes, then can you provide me with the table structure you are using for Letter as well as the migration you have written for that particular table?如果是,那么您能否向我提供您用于 Letter 的表结构以及您为该特定表编写的迁移?

I am not sure but it seems like you are passing an array $reciever_id instead of string and/or JSON string.我不确定,但您似乎传递的是数组$reciever_id reciever_id 而不是字符串和/或 JSON 字符串。

Also, if the table in the screenshot you provided, is to be used as the log, then I would suggest to iterate through $receiver_id and make a separate entry for each of the receiver if possible.此外,如果您提供的屏幕截图中的表格将用作日志,那么我建议您遍历$receiver_id并尽可能为每个接收者创建一个单独的条目。 This could be a better approach I think.我认为这可能是一个更好的方法。

EDIT: After reading your comment, I am modifying my answer as below: In that case, you should either handle the request with foreach loop as below:编辑:阅读您的评论后,我将我的答案修改如下:在这种情况下,您应该使用 foreach 循环处理请求,如下所示:

$receiver_ids = $request->receive_ids
foreach($receiver_ids as $receiver_id)
{
    Letter::create([
        'indicator_id' => $request['indicator_id'],
        'sender_id' => auth()->user()->id,
        'recieve_id' => $receiver_id,
        'title' => $request['title'],
        'image' => 'default.png',
        'description' => $request['description'],
        'date' => $request['date'],
        'text' => $request['text'],
    ]);
}

Put this code in your controller.将此代码放入您的 controller 中。 And let me know.让我知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM