[英]how to add extra data with sync method laravel
我正在使用 Laravel 并且我有三个表:products、 features 和 feature_product 第三个表有一个额外的列“值”,我想在同步时添加每个功能的值
所以同步方法在没有价值的情况下工作,但每当我想发送价值时,它都会给我错误
这是我的代码
if($request->get('feature')){
foreach($request->get('feature') as $featureName)
{
$feature = Feature::find($featureName);
if($feature)
{
$featureIds[] = $feature->id;
}
}
$product->features()->sync($featureIds);
}
这是我的错误
一般错误:1364 字段“值”没有默认值(SQL:插入到
feature_product
(feature_id
,product_id
) values (11, 99))
我知道这是因为我没有为此发送价值,我想知道我该怎么做
您缺少同步的枢轴值,这就是您收到此错误的原因。
if($request->get('feature')){
$featureIds = array();
foreach($request->get('feature') as $featureName)
{
$feature = Feature::find($featureName);
if($feature){
$featureIds[$feature->id] = ['value'=>'yourvalue'];
}
}
$product->features()->sync($featureIds);
}
尝试使这种数组同步。
$product->features()->sync( array(
1 => array( 'value' => 'xyz' ),
2 => array( 'value' => 'abc' ),
...
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.