【问题标题】:Laravel vue Column not found: 1054 UnknownLaravel vue 未找到列:1054 未知
【发布时间】: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


    【解决方案1】:

    这是因为您的类别数组是一个二维数组。现在,当您同步该数据时,您的代码如下所示。

    $product->categories()->sync([0] => ['0' => ''], false);
    

    这就是错误显示Column not found: 1054 Unknown column '0' in 'field list' 的原因。

    现在,要解决您的问题,首先您的类别值必须是这样的

    $categories = [2, 1]; // like this one
    $categories = [[2], [1]]; // not this one
    

    您可以在同步之前首先重新构建您的类别数组,通过这样做

    $categories = [];
    foreach ($request->categories$key => $category) {
           $categories [] = $category[0];
    }
    
    $product->categories()->sync($categories, false);
    

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2016-04-29
      • 2021-08-08
      • 2019-11-11
      • 2018-02-21
      • 2015-12-08
      • 2018-11-02
      • 2019-10-02
      相关资源
      最近更新 更多