php 如何在 Laravel 5.2 中存储多选值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38288899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store multi select values in Laravel 5.2
提问by dollar
I have a form which stores News.
我有一个存储新闻的表格。
Here I am using Multiselect and I want to save all the selected option in the table as say Users,staff,cinemahall as a string.
在这里,我使用 Multiselect,我想将表中的所有选定选项保存为一个字符串,比如用户、员工、电影院。
My controller function to store values is
我存储值的控制器功能是
public function store(Request $request)
{
$input=$request->all();
General_news::create($input);
return redirect()->back();
}
This function store the all submitted fields but for multiselect it stores only last option i.e cinemahall
此功能存储所有提交的字段,但对于多选,它仅存储最后一个选项,即 Cinemahall
When form is submitted all selected options are displayed but it's not saving in database table properly.
提交表单时,所有选定的选项都会显示,但没有正确保存在数据库表中。
help me to solve this issue.
帮我解决这个问题。
回答by Chay22
Make sure you set the name attribute to an array
确保将 name 属性设置为数组
<select multiple="multiple" name="news[]" id="news">
To store it as string separated by commas
将其存储为以逗号分隔的字符串
$news = $request->input('news');
$news = implode(',', $news);
You have a string which will look like Users,staff,cinemahall
. Now, instead to retrieve all input, you may need to retrieve it one by one, since you need to mutate the news
value. Additionally, you can also use except()
method to exclude news
from mass getting all value.
你有一个看起来像Users,staff,cinemahall
. 现在,为了检索所有输入,您可能需要一一检索它,因为您需要改变news
值。此外,您还可以使用except()
方法news
从批量获取所有值中排除。
$news = $request->input('news');
$news = implode(',', $news);
$input = $request->except('news');
//Assign the "mutated" news value to $input
$input['news'] = $news;
General_news::create($input);
return redirect()->back();
回答by Bdwey
Thanks @Chay22
谢谢@Chay22
you could also use Mutators and Accessor https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
你也可以使用 Mutators 和 Accessor https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
public function setFooAttribute($value)
{
$this->attributes['foo'] = implode(',',$value);
}
public function getFooAttribute($value)
{
return explode(',',$value);
}
回答by Ruffles
If you are using a multiselect, that probably means that you need a many to many relationship and a pivot table. Kind of like how posts
can belong to many tags
and tags
can belong to many posts
.
如果您使用的是多选,那可能意味着您需要多对多关系和数据透视表。有点像怎么posts
可以属于很多tags
又tags
可以属于很多posts
。
In your case this would probably be between news
and the news_types
tables.
在您的情况下,这可能news
在news_types
表之间。