【发布时间】:2023-02-03 00:08:47
【问题描述】:
看我的代码sn-p.我想将所有值 1,2,3 插入数据库
我有color table和product table
这些是我的桌子
颜色:|标题 |另一个标题 | | ------ | -------------- | |第一 |行 | |第二 |行 |
产品:|编号|姓名|颜色编号| |---- |------| ------| | 1 |电话| 1 | | 2 |笔记本电脑| 2 |
在product table如何给产品选择多于一种颜色
我试着做这个但失败了
|编号|姓名|颜色编号|
|---- |------| ------|
| 1 |电话| 1 3 |
| 2 |笔记本电脑| 2 4 |
我想给产品两种颜色,因为我想使用 ColorController 中的代码显示产品的颜色
这些是我的控制器
颜色控制器:
class productColorController extends Controller {
...
public function store(Request $request) {
$colors = collect($request->color); // Here it gives the color are getting from the multi select you can see it in code snippet
$color = productColor::create([
'color' => $colors['color'], // here i want to create all of the color are getting from request and save to database but when i try this i see only one color was saved to database
]);
}
// The code to show all colors
$getcolor = productColor::where('id' , 1)->get(); // I Want To Show All Colors User selected in id 1
}
问题的结论:当用户选择多种颜色时,我想将其保存在数据库中并将所有颜色显示给管理员
<select data-placeholder="Please Choose Color" multiple name="" class="select2 form-control">
<optgroup label="Please Choose Color">
<option value='black'>
Black
</option>
<option value='white'>
White
</option>
<option value='gray'>
Gray
</option>
<option value='blue'>
Blue
</option>
>
</optgroup>
</select>
【问题讨论】:
-
最好的方法是创建一对多关系,创建数据透视表并与产品和颜色建立关系。
-
是的,我有一对多关系,但我无法保存到表格中的颜色
-
你需要多对多,而不是一对多的关系
-
@workservice 你能给我举个例子吗
-
我在下面回答了@BlexChex 实现它,它会像一个魅力
标签: laravel select where-clause