【发布时间】:2020-05-13 09:59:52
【问题描述】:
我正在尝试将 id 数组发送到后端并使用 sync 方法存储它们,但它返回
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `category_products` (`category_id`, `product_id`, `0`) values (0, 12, 2))
代码
product model
public function categories(){
return $this->belongsToMany(Category::class,'category_products', 'product_id', 'category_id');
}
category model
public function products(){
return $this->belongsToMany(Product::class);
}
controller store function
//getting other inputs...
$product->save();
$product->categories()->sync($request->categories, false);
data that sent to back-end
注意:可能值得一提的是我正在使用 vueJs 来发送 数据,它不是基于刀片的。
Component HTML
<el-cascader
v-model="form.categories"
style="width: 100%;"
:options="cats"
:props="{
multiple: true,
checkStrictly: true,
value: 'id',
label: 'name',
}"
clearable
filterable>
</el-cascader>
Component Script
data() {
return {
brands: [],
cats: [],
tags: [],
site_name: process.env.MIX_APP_NAME,
site_url: process.env.MIX_APP_URL,
dialogImageUrl: '',
dialogVisible: false,
disabled: false,
form: {
name: '',
slug: '',
price: '',
new_price: '',
sku: '',
qty: 1,
active: '',
photo: '',
photos: [],
shortDesc: '',
longDesc: '',
tags: [],
brand_id: '',
categories: [], // this will send to back-end
user_id: '',
seoTitle: '',
seoTags: '',
seoPhoto: '',
seoDescription: '',
variations: [],
options: [],
condition: '',
isbn: '',
ean: '',
upc: '',
},
}
},
methods: {
// send product data
onSubmit(e) {
e.preventDefault();
// axios.defaults.headers.common['Authorization'] = `Bearer ${await this.$auth.getAccessToken()}`
axios.post('/api/admin/products/store', this.form)
.then(res => {
console.log(res.data.success);
this.$notify({
title: 'Hooray!',
message: res.data.success,
offset: 100,
type: 'success'
});
// this.$router.push({name: 'adminProducts'});
this.form = {
name: "",
slug: "",
price: "",
new_price: "",
sku: "",
qty: '',
active: "",
photo: "",
shortDesc: "",
longDesc: "",
tags: [],
brand_id: "",
categories: [],
seoTitle: "",
seoTags: [],
seoPhoto: "",
seoDescription: "",
variations: [],
user_id: this.form.user_id
};
})
.catch(error => {
var errors = error.response.data;
let errorsHtml = '<ol>';
$.each(errors.errors,function (k,v) {
errorsHtml += '<li>'+ v + '</li>';
});
errorsHtml += '</ol>';
this.$notify.error({
title: 'Error',
dangerouslyUseHTMLString: true,
message: errorsHtml
});
})
},
}
有什么想法吗?
更新
我已经解决了这个代码的问题
foreach($request->categories as $caat){
$product->categories()->sync($caat, false);
}
现在它保存了我的产品类别,但我个人对此并不满意!我想使用默认同步方法$product->categories()->sync($request->categories, false);
,不需要任何循环。
请分享你的想法。
【问题讨论】:
标签: javascript php laravel vue.js vuejs2