Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 5.7-枢轴台附件()_Laravel_Laravel 5_Pivot Table - Fatal编程技术网

Laravel 5.7-枢轴台附件()

Laravel 5.7-枢轴台附件(),laravel,laravel-5,pivot-table,Laravel,Laravel 5,Pivot Table,我无法使attach()在我的设置中工作 每个用户可以有许多订单s,这些订单可以有许多产品s User.php 公共职能指令() { 返回$this->hasMany(订单::类); } Order.php 公共功能用户() { 返回$this->belongsTo(用户::类); } 公共功能产品() { 返回$this->belongtomany(产品::类) ->withTimestamps() ->withPivot(“数量”); } Product.php 公共职能指令() { 返

我无法使
attach()
在我的设置中工作

每个
用户
可以有许多
订单
s,这些订单可以有许多
产品
s

User.php

公共职能指令()
{
返回$this->hasMany(订单::类);
}
Order.php

公共功能用户()
{
返回$this->belongsTo(用户::类);
}
公共功能产品()
{
返回$this->belongtomany(产品::类)
->withTimestamps()
->withPivot(“数量”);
}
Product.php

公共职能指令()
{
返回$this->belongtomany(订单::类)
->withTimestamps()
->withPivot(“数量”);
}
我有一个
create.blade.php
,用于显示所有可用产品,并且可以选择每个产品的数量,这将保存在透视表上

create.blade.php

{{Form::open(数组('url'=>'/orders/store'))}
@foreach($products as$product)
{{$product->name}

{{$product->description}

{{Form::text('qty',0,['type'=>'tel'])} @endforeach {{Form::select('delivery_day',['M'=>'星期一','W'=>'星期三'), 空,['placeholder'=>'Delivery Day']) }} {{Form::submit('placeorder')} {{Form::close()}}
当我提交请求时,仅保存
Order
表中的字段

公共函数存储(请求$Request)
{
//证实
$request->validate([
“数量”=>“整数”,
]);
#创建新订单
$order=新订单;
$id=Auth::user()->id;
$order->user\u id=$id;
//传入表单参数(非数量)
auth()->user()->orders()->save($order);//保存订单
#枢轴连接()
我迷路了
return redirect('complete')->带有('success','Order has created');
}
我相信这是一个事实,我正在尝试以一种形式传递多个产品(我相信我应该能够在使用
attach()
时作为arry传递)

我尝试了各种解决方案,但仍然无法填充数据透视表

我最后一次尝试是通过一个隐藏字段传递
产品\u id
,然后运行这个

$attach_data=[];
对于($i=0;$i$qtys[$i]];
$order->product_id()->attach($attach_data);
但是,这不起作用。

根据文档()这是附加多个项目的一种方法:

$user->roles()->attach([
  1 => ['expires' => $expires],
  2 => ['expires' => $expires]
]);
因此,您必须修改以下内容:

# Create New Order
$order = new Order;
$id = Auth::user()->id;
$order->user_id = $id;
$order->save();

// change this for your array of ids
$products_to_sync_ids = [1,3,23];

$sync_data = [];
$qty = 1; <----- I dont know if you are inserting them with the same qty
for($i = 0; $i < count($products_to_sync_ids); $i++))
   $sync_data[$products_to_sync_ids[$i]] = ['qty' => $qty];

$order->products()->sync($sync_data);
#创建新订单
$order=新订单;
$id=Auth::user()->id;
$order->user\u id=$id;
$order->save();
//为您的ID数组更改此选项
$products_to_sync_id=[1,3,23];
$sync_data=[];
$qty=1;$qty];
$order->products()->sync($sync\u数据);

尝试并检查产品是否正确插入透视表,然后修改代码以插入每个代码及其数量。

您如何尝试使用
attach()
?您可以将代码添加到您的问题中吗?我非常接近,希望这对其他人有所帮助。