【问题标题】:Laravel VueJs store array from axios request in laravel controllerLaravel VueJs 在 laravel 控制器中存储来自 axios 请求的数组
【发布时间】:2020-08-11 03:03:54
【问题描述】:

我有一个 laravel 5.7 应用程序,它使用 VueJS 2.0 作为前端。 我有两个具有多对多关系的表:commandes 和 produits。我目前正在尝试将数据传递到我的 commandes 表中,但出现此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `commande_produit` (`0`, `commande_id`, `produit_id`) values (3, , 0))

如果有人能告诉我如何解决甚至指出正确的方向,我将不胜感激。

html模板:

<template>
   <div class="container">
       <div class="row justify-content-center mt-5" v-if="$gate.isAdminOrVendeur()">
           <div class="col-md-12">
               <form class="" @submit.prevent="envoyer()" >
               <table class="table table-bordered table-striped table-responsive">
                   <thead class="thead-dark">
                       <tr>
                           <th class="col-sm-4">Produit</th>
                           <th class="col-sm-2">Quantité</th>
                           <th class="col-sm-2">montant</th>
                           <th class="col-sm-2">Total</th>
                           <th class="col-sm-1"></th>
                           <th class="col-sm-1"></th>
                       </tr>
                   </thead>
                   <tbody>
                   <tr v-for="(commande, index) in commandes" :key="index">
                       <td>{{ commande.produit_id }}</td>
                       <td>{{ commande.quantite }}</td>
                       <td>{{ commande.montant }} F</td>
                       <td>{{ (commande.quantite * commande.montant).toFixed(2) }} F</td>
                       <td><a class="btn btn-info btn-block" @click="modifier(index)">Modifier</a></td>
                       <td><a class="btn btn-warning btn-block" @click="supprimer(index)">Poubelle</a></td>
                   </tr>
                   <tr>
                       <td colspan="3"></td>
                       <td><strong> F </strong></td>
                       <td colspan="2"></td>
                   </tr>
                   <tr>
                       <td>
                           <div class="form-group">                            
                           <select v-model="form.produit_id" name="produit_id" class="form-control">
                               <option v-for="produit in produits.data" :key="produit.id" v-bind:value="produit.id">{{ produit.designation }}</option>                                
                           </select>

                       </div>
                       </td>
                       <td><input type="text" class="form-control" v-model="form.quantite"></td>
                       <td><input type="text" class="form-control" v-model="form.montant"></td>
                       <td colspan="3"><a class="btn btn-primary btn-block" @click="ajouter">Ajouter</a></td>
                   </tr>
                   </tbody>
                   <tfoot>
                   <a class="button btn btn-xs btn-warning" @click="toutPoubelle">Tout à la poubelle</a>
                   <button class="button btn btn-xs btn-success" type="submit">Valider</button>
                   </tfoot>
               </table>
           </form>
           <div class="panel panel-danger" v-show="poubelle.length">
               <div class="panel-heading">Poubelle</div>
               <table class="table table-bordered table-striped table-responsive">
                   <thead>
                   <tr>
                       <th class="col-sm-4">Produit</th>
                       <th class="col-sm-2">Quantité</th>
                       <th class="col-sm-2">montant</th>
                       <th class="col-sm-2">Total</th>
                       <th class="col-sm-1"></th>
                       <th class="col-sm-1"></th>
                   </tr>
                   </thead>
                   <tbody>
                   <tr v-for="(commande, index) in poubelle" :key="index">
                       <td>{{ commande.produit }}</td>
                       <td>{{ commande.quantite }}</td>
                       <td>{{ commande.montant }} F</td>
                       <td>{{ (commande.quantite * commande.montant).toFixed(2) }} F</td>
                       <td><a class="btn btn-success btn-block" @click="retablir(index)">Rétablir</a></td>
                       <td><a class="btn btn-danger btn-block" @click="eliminer(index)">Supprimer</a></td>
                   </tr>
                   </tbody>
               </table>
               <div class="panel-footer">
                   &nbsp;
                   <div class="btn-group">
                       <a class="button btn btn-xs btn-success" @click="toutRetablir">Tout rétablir</a>
                       <a class="button btn btn-xs btn-danger" @click="toutEliminer">Tout supprimer</a>
                   </div>
               </div>
           </div>
           </div>            
       </div>
   </div>
</template>

我的 vue 实例:

<script>
    export default {
        data () {
            return {                
            commandes: [],
            poubelle: [], 
            produits: {}, 
            form: new Form({                                  
                produit_id : '',                    
                quantite : '',                    
                montant: '',                   
            })       
            }
        },

        methods: {      
            ajouter() {
                this.commandes.push({produit_id: this.form.produit_id, quantite: this.form.quantite, montant: this.form.montant});
                this.form = {};
                this.commandes.sort(ordonner);
            },

            modifier(index) {
                this.form.produit_id = this.commandes[index].produit_id;
                this.form.quantite = this.commandes[index].quantite;
                this.form.montant = this.commandes[index].montant;
                this.commandes.splice(index, 1);
            },

            supprimer(index) {
                this.poubelle.push(this.commandes[index]);
                this.commandes.splice(index, 1);
                this.poubelle.sort(ordonner);
            },

            retablir(index) {
                this.commandes.push(this.poubelle[index]);
                this.poubelle.splice(index, 1);
                this.commandes.sort(ordonner);
            },

            eliminer(index) {
                this.poubelle.splice(index, 1);
            },

            toutPoubelle() {
                this.poubelle = this.poubelle.concat(this.commandes);
                this.poubelle.sort(ordonner);
                this.commandes = [];
            },

            toutRetablir() {
                this.commandes = this.commandes.concat(this.poubelle);
                this.commandes.sort(ordonner);
                this.poubelle = [];
            },

            toutEliminer() {
                this.poubelle = [];
            },

            loadProduits(){
                //if(this.$gate.isAdminOrComptable()){
                    axios.get("api/produit").then(({ data }) => (this.produits = data));
                //}
            },

            envoyer() {
                axios.post('api/commande', {commande: this.commandes});
                this.commandes = [];        
            },       
        },
        mounted() {
            this.loadProduits();
            console.log('Component mounted.')
        }
    }

    var ordonner = function (a, b) {
        return (a.commande.toUpperCase() > b.commande.toUpperCase())
    };
</script>

这是命令模型:

class Commande extends Model
{
    protected $fillable = ['commande'];

    public function produits()
    {
    return $this->belongsToMany('App\Models\Produit');
    }
}

和产品模型:

class Produit extends Model
{
    protected $fillable = ['designation'];

    public function commandes()
    {
        return $this->belongsToMany('App\Models\Commande');
    }
}

命令控制器 store() 方法:

 public function store(Request $request)
    {

        $this->validate($request,[
            'commande' => 'required',
        ]);

        $commande = new Commande();

        $commande->produits()->attach([$request->commande]);

        $commande->save();

    }

【问题讨论】:

  • 请问dd([$request-&gt;commande]) 好吗?
  • 我认为你没有正确使用attach()方法,看看:laravel.com/docs/7.x/…
  • 这里是dd结果array:2 [ 0 =&gt; array:3 [ "produit_id" =&gt; 2 "quantite" =&gt; "3" "montant" =&gt; "4" ] ]

标签: javascript php laravel vue.js axios


【解决方案1】:

她是最终的store()函数:

public function store(Request $request)
    {

        $this->validate($request,[
            'commande' => 'required',
        ]);

        $commande = new Commande();

        $commande->save();

        $produitsId = array_column($request->commande, 'produit_id');

        $commande->produits()->attach($produitsId);

    }

希望对某人有所帮助。

【讨论】:

    【解决方案2】:

    在您的代码中,有几件事可能无法按预期工作:

    1. 您正试图将produits 附加到一个不存在的模型上。

    通过使用new Commande,您只是在准备对象Commande,还没有将它保存到数据库中。你不能在上面附加任何东西,因为它还没有id

    解决方案:使用Create 而不是New

    1. attach()方法使用不当

    根据文档 (https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships) attach() 需要一个 id 数组。您正在尝试传递自定义数组,因此该方法将不起作用。

    解决方案:从 $request-&gt;command 中提取 Id,然后使用 attach()

    【讨论】:

    • 非常感谢,我会尝试您的解决方案。
    • Pas de soucis ? 告诉我
    • 只用英文对话,让别人听懂。事实上save() 也可以。
    • 如果您的问题得到解答,请不要忘记接受解决方案?
    • Hi:) 对于解决方案 1,我没有 create() 函数的参数,所以我只是在 attach() 之前执行 save()。它工作正常,但我遇到了新问题:`SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败
    猜你喜欢
    • 2018-01-04
    • 2019-04-20
    • 2020-07-15
    • 2020-08-09
    • 1970-01-01
    • 2013-11-29
    • 2021-01-20
    • 2019-02-25
    • 2021-12-26
    相关资源
    最近更新 更多