如何将一个表中的用户名数据自动发布到另一个表中? VueJs + Laravel + MySQL

问题描述

我有一个用户表,该表在Laravel Vue应用程序的数据库(sql)的用户部分显示已注册的用户。现在,我有一个雇员表,其中有一个用于业务信息的表格。发布Emppleado表单时,我需要使用用户表中的名称自动填充名为empuser的数据库中存在的字段之一。提交表单时,出现一条SQL错误,提示我没有empuser字段的默认值。 我在本地开发中将phpmyadmin与SQL一起使用。就我而言,不是sql不起作用,而是我不确定如何在这种类型的环境(即VueJs和Laravel)中建立关系。我遇到的错误是"SQLSTATE[HY000]: General error: 1364 Field 'empuser' doesn't have a default value (SQL: insert into empleados ( emprfc , ...等。 数据库迁移: User_table:

public function up()
    {
        Schema::create('users',function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('type')->default('user');
            $table->mediumText('bio')->nullable();
            $table->string('photo')->default('profile.png');
            $table->rememberToken();
            $table->timestamps();
        });
    }

员工表

   public function up()
    {
        Schema::create('empleados',function (Blueprint $table) {
            $table->id();
$table->string('emprfc',20)->unique();
$table->string('empnombre',75);
$table->string('empcalle',100)->nullable();
$table->string('empcolonia',50)->nullable();
$table->string('empciudad',50);
$table->string('empestado',50);
$table->string('empcpostal',5);
$table->string('emppais',25);
$table->string('empstatus',1)->default('1');
$table->bigInteger('empuser');
$table->bigInteger('empregby');
$table->timestamps();
$table->index('empciudad');
$table->index('empestado');
$table->index('empcpostal');
$table->index('emppais');
$table->index('empuser');
$table->index('empregby');
        });
    }

Users.vue

<template>
  <div class="container-fluid">
    <div class="row pt-3">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">Tablero de Usuarios</h3>

            <div class="card-tools">
              <!-- <button class="btn btn-success" data-toggle="modal" data-target="#addNew"> -->
              <button class="btn btn-success" @click="newModal">
                <i class="fas fa-user-plus"></i> Añadir Nuevo
                Usuario
              </button>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body table-responsive p-0">
            <table class="table table-hover text-nowrap">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Nombre</th>
                  <th>Correo</th>
                  <th>Rol</th>
                  <th>Registrado</th>
                  <th>Modificar</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in users" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.name }}</td>
                  <td>{{ user.email }}</td>
                  <td>{{ user.type | upText }}</td>
                  <td>{{ user.created_at | myDate }}</td>
                  <td>
                    <a class="btn btn-primary" href="#" @click="editModal(user)">
                      <i class="fas fa-edit"></i>
                    </a>
                    <a class="btn btn-danger" href="#" @click="deleteUser(user.id)">
                      <i class="fas fa-trash"></i>
                    </a>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- /.card-body -->
        </div>
        <!-- /.card -->
      </div>
    </div>
    <form @submit.prevent="editmode ? updateUser() : createUser()">
      <!-- Modal -->
      <div
        class="modal fade"
        id="addNew"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 v-show="!editmode" class="modal-title" id="exampleModalLabel">Añadir Nuevo</h5>
              <h5
                v-show="editmode"
                class="modal-title"
                id="exampleModalLabel"
              >Actualizar datos de Usuario</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <input
                  v-model="form.name"
                  type="text"
                  name="name"
                  placeholder="Nombre de Usuario"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('name')
                                    }"
                />
                <has-error :form="form" field="name"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.email"
                  type="email"
                  name="name"
                  placeholder="Correo Electrónico"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('email')
                                    }"
                />
                <has-error :form="form" field="email"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.bio"
                  type="text"
                  name="bio"
                  placeholder="Bio breve de Usuario (Opcional)"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('bio')
                                    }"
                />
                <has-error :form="form" field="name"></has-error>
              </div>
              <div class="form-group">
                <select
                  id="type"
                  v-model="form.type"
                  name="type"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('type')
                                    }"
                >
                  <option value>Eliges el Rol de Usuario</option>
                  <option value="admin">Admin</option>
                  <option value="user">Usuario Estándar</option>
                  <option value="author">Autor</option>
                </select>
                <has-error :form="form" field="name"></has-error>
              </div>
              <div class="form-group">
                <input
                  v-model="form.password"
                  type="password"
                  name="password"
                  placeholder="Contraseña"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has(
                                            'password'
                                        )
                                    }"
                />
                <has-error :form="form" field="password"></has-error>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
              <button v-show="editmode" type="submit" class="btn btn-success">Actualizar</button>
              <button v-show="!editmode" type="submit" class="btn btn-primary">Crear</button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      updateUser() {
        this.$Progress.start();
        this.form
          .put("api/user/" + this.form.id)
          .then(() => {
            // successfull
            $("#addNew").modal("hide");
            swal.fire("Actualizó","Datos del usuario actualizados","success");
            this.$Progress.finish();
            Fire.$emit("AfterCreate");
          })
          .catch(() => {
            // Unsuccessfull
            this.$Progress.fail();
          });
      },editmode: true,users: {},form: new Form({
        id: "",name: "",email: "",password: "",type: "",bio: "",photo: "",}),};
  },methods: {
    editModal(user) {
      this.editmode = true;
      this.form.reset();
      $("#addNew").modal("show");
      this.form.fill(user);
    },newModal() {
      this.editmode = false;
      this.form.reset();
      $("#addNew").modal("show");
    },deleteUser(id) {
      swal
        .fire({
          title: "¿Estas seguro?",text: "¡No podrás revertir esto!",icon: "warning",showCancelButton: true,confirmButtonColor: "#3085d6",cancelButtonColor: "#d33",confirmButtonText: "¡Sí,Bórralo!",})
        .then((result) => {
          // Send Request to the server

          this.form
            .delete("api/user/" + id)
            .then(() => {
              if (result.value) {
                swal.fire(
                  "Borrado!","El usuario ha sido eliminado.","success"
                );
                Fire.$emit("AfterCreate");
              }
            })
            .catch(() => {
              swal("¡Fallo!","Algo salió mal","warning");
            });
        });
    },loadUsers() {
      axios.get("api/user").then(({ data }) => (this.users = data.data));
    },createUser() {
      this.$Progress.start();
      this.form
        .post("api/user")
        .then(() => {
          Fire.$emit("AfterCreate");
          $("#addNew").modal("hide");

          toast.fire({
            icon: "success",title: "Usuario creado con éxito",});
          this.$Progress.finish();
        })
        .catch(() => {
          this.$Progress.fail();
          toast.fire({
            icon: "error",title: "Usuario no fue creado.",});
        });
    },},created() {
    this.loadUsers();
    Fire.$on("AfterCreate",() => {
      this.loadUsers();
    });
  },};
</script>

UserController.php

<?php
namespace App\Http\Controllers\API;  
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function index()
    {
        return User::latest()->paginate(10);
    }

    public function store(Request $request)
    {

        $this->validate($request,[
            'name' => 'required|string|max:191','email' => 'required|string|email|max:255|unique:users','password' => 'required|string|min:8'
        ]);
        return User::create([
            'name' => $request['name'],'email' => $request['email'],'type' => $request['type'],'bio' => $request['bio'],'photo' => $request['photo'],'password' => Hash::make($request['password']),]);
    }
 
    public function empleado()
    {
        return auth('api')->user();
    }

    public function updateProfile(Request $request)
    {
        $user =  auth('api')->user();

        if($request->photo) {
           $name = time().'.' . explode('/',explode(':',substr($request->photo,strpos ($request->photo,';')))[1])[1]; 
           \Image::make($request->photo)->save(public_path('img/profile/').$name);
        }
        // return ['message' => 'Éxito'];
    }

    public function profile()
    {
        return auth('api')->user();
    }

    public function show($id)
    {
        //
    }

    public function update(Request $request,$id)
    {
        $user = User::findOrFail($id);

        $this->validate($request,'email' => 'required|string|email|max:255|unique:users,email,'.$user->id,'password' => 'sometimes|min:8'
        ]);

        $user->update($request->all());
        return ['message' => 'Actualizó los datos del usuario.'];
    }
    public function destroy($id)
    {
        $user = User::findOrFail($id);

        // Delete the user
        $user->delete();

        return ['message' => 'Usuario Eliminado'];
    }
}

User.php

<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
    use  HasApiTokens,Notifiable;

    protected $fillable = [
        'name','email','password','bio','photo','type'
    ];

    protected $hidden = [
        'password','remember_token',];

    protected $casts = [
        'email_verified_at' => 'datetime',];
}

Empleado.vue

<template>
  <div class="container-fluid">
    <div class="row pt-3">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">Tablero de Emmpleados</h3>
            <div class="card-tools">
              <!-- <button class="btn btn-success" data-toggle="modal" data-target="#addNew"> -->
              <button class="btn btn-success" @click="newModal">
                <i class="fas fa-user-plus"></i> Añadir Nuevo
                Empleado
              </button>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body table-responsive p-0">
            <table class="table table-hover text-nowrap">
              <thead>
                <tr>
                  <th>RFC</th>
                  <th>Nombre</th>
                  <th>Calle</th>
                  <th>Colonia</th>
                  <th>Ciudad</th>
                  <th>Estado</th>
                  <th>Código Postal</th>
                  <th>País</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="empleado in empleados" :key="empleado.id">
                  <td>{{ empleado.emprfc }}</td>
                  <td>{{ empleado.empnombre }}</td>
                  <td>{{ empleado.empcalle }}</td>
                  <td>{{ empleado.empcolonia }}</td>
                  <td>{{ empleado.empestado }}</td>
                  <td>{{ empleado.empcpostal }}</td>
                  <td>{{ empleado.pais }}</td>
                  <td>
                    <a class="btn btn-primary" href="#" @click="editModal(empleado)">
                      <i class="fas fa-edit"></i>
                    </a>
                    <a class="btn btn-danger" href="#" @click="deleteEmpleado(empleado.id)">
                      <i class="fas fa-trash"></i>
                    </a>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- /.card-body -->
        </div>
        <!-- /.card -->
      </div>
    </div>
    <form @submit.prevent="editmode ? updateEmpleado() : createEmpleado()">
      <!-- Modal -->
      <div
        class="modal fade"
        id="addNew"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 v-show="!editmode" class="modal-title" id="exampleModalLabel">Añadir Nuevo</h5>
              <h5
                v-show="editmode"
                class="modal-title"
                id="exampleModalLabel"
              >Actualizar datos de Empleado</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <input
                  v-model="form.emprfc"
                  type="text"
                  name="emprfc"
                  placeholder="RFC"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('emprfc')
                                    }"
                />
                <has-error :form="form" field="emprfc"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.empnombre"
                  type="text"
                  name="empnombre"
                  placeholder="Nombre"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('empnombre')
                                    }"
                />
                <has-error :form="form" field="empnombre"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.empcalle"
                  type="text"
                  name="empcalle"
                  placeholder="Calle"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has('empcalle')
                                    }"
                />
                <has-error :form="form" field="empcalle"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.empcolonia"
                  type="text"
                  name="empcolonia"
                  placeholder="Colonia"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has(
                                            'empcolonia'
                                        )
                                    }"
                />
                <has-error :form="form" field="empcolonia"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.empciudad"
                  type="text"
                  name="empciudad"
                  placeholder="Ciudad"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has(
                                            'empciudad'
                                        )
                                    }"
                />
                <has-error :form="form" field="empciudad"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.empestado"
                  type="text"
                  name="empestado"
                  placeholder="Estado"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has(
                                            'empestado'
                                        )
                                    }"
                />
                <has-error :form="form" field="empestado"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.empcpostal"
                  type="text"
                  name="empcpostal"
                  placeholder="Código Postal"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has(
                                            'empcpostal'
                                        )
                                    }"
                />
                <has-error :form="form" field="empcpostal"></has-error>
              </div>

              <div class="form-group">
                <input
                  v-model="form.emppais"
                  type="text"
                  name="emppais"
                  placeholder="País"
                  class="form-control"
                  :class="{
                                        'is-invalid': form.errors.has(
                                            'emppais'
                                        )
                                    }"
                />
                <has-error :form="form" field="emppais"></has-error>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
              <button v-show="editmode" type="submit" class="btn btn-success">Actualizar</button>
              <button v-show="!editmode" type="submit" class="btn btn-primary">Crear</button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      updateEmpleado() {
        this.$Progress.start();
        this.form
          .put("api/empleado/" + this.form.id)
          .then(() => {
            // successfull
            $("#addNew").modal("hide");
            swal.fire("Actualizó",empleados: {},emprfc: "",empnombre: "",empcalle: "",empcolonia: "",empciudad: "",empestado: "",empcpostal: "",emppais: "",methods: {
    editModal(empleado) {
      this.editmode = true;
      this.form.reset();
      $("#addNew").modal("show");
      this.form.fill(empleado);
    },deleteEmpleado(id) {
      swal
        .fire({
          title: "¿Estas seguro?",})
        .then((result) => {
          // Send Request to the server

          this.form
            .delete("api/empleado/" + id)
            .then(() => {
              if (result.value) {
                swal.fire(
                  "Borrado!","El empleado ha sido eliminado.",loadEmpleados() {
      axios
        .get("api/empleado")
        .then(({ data }) => (this.empleados = data.data));
    },createEmpleado() {
      this.$Progress.start();
      this.form
        .post("api/empleado")
        .then(() => {
          Fire.$emit("AfterCreate");
          $("#addNew").modal("hide");
          toast.fire({
            icon: "success",title: "Empleado creado con éxito",title: "Empleado no fue creado.",created() {
    this.loadEmpleados();
    Fire.$on("AfterCreate",() => {
      this.loadEmpleados();
    });
  },};
</script>

EmpleadoController.php

<?php  
namespace App;  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;    
class Empleado extends Authenticatable
{
    use  HasApiTokens,Notifiable;

    protected $fillable = [
        'emprfc','empnombre','empcalle','empcolonia','empciudad','empestado','empcpostal','emppais'
    ];    
    protected $hidden = [
        //
    ];    
    protected $casts = [
        'email_verified_at' => 'datetime',];
}

Empleado.php

<?php    
namespace App;    
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;    
class Empleado extends Authenticatable
{
    use  HasApiTokens,Notifiable;
    protected $fillable = [
        'emprfc','emppais'
    ];   

    protected $hidden = [
        //
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',];
}

Image of network data tab showing me as user.

在这里,您可以看到我的用户名正确返回。

Here is the Employee data entry form for the user (me in this case).

这里我有添加员工数据的表格。

Image of network error

在此图像中,您可以看到我收到的错误类型。

如果我缺少任何代码,请告诉我,以便我可以编辑查询。预先谢谢你。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...