使用 Laravel 的 Eloquent 向数据库发送数据的问题

Posted

技术标签:

【中文标题】使用 Laravel 的 Eloquent 向数据库发送数据的问题【英文标题】:Problem with sending data to DB using Laravel's Eloquent 【发布时间】:2020-11-24 06:49:31 【问题描述】:

某些数据未从表单视图传输到数据库表(发票)。我无法从其他控制器向该表(发票)发送其他表(表格)的数据。并且软删除也不适用于此表。

这是此表 2020_07_29_102453_invoices.php 的迁移文件:

    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class Invoices extends Migration

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    
        Schema::create('invoices', function (Blueprint $table) 
            $table->increments('id');
            $table->string('invoicenumber')->nullable();
            $table->date('invoicedate')->nullable();
            $table->date('selldate')->nullable();
            $table->integer('user_id')->unsigned()->nullable();
            $table->integer('form_id')->unsigned()->nullable();                        
            $table->integer('currency_id')->unsigned()->nullable();            
            $table->integer('proform_id')->unsigned()->nullable(); 
            $table->string('paymentmethod')->nullable();
            $table->date('paymentdate')->nullable();
            $table->string('status')->nullable();
            $table->string('comments')->nullable();
            $table->string('city')->nullable();
            $table->string('paid')->nullable();
            $table->string('autonumber')->nullable();
            $table->string('automonth')->nullable();
            $table->string('autoyear')->nullable();
            $table->string('name')->nullable();
            $table->string('PKWIU')->nullable();
            $table->string('quantity')->nullable();
            $table->string('unit')->nullable();            
            $table->string('netunit')->nullable();
            $table->string('nettotal')->nullable();
            $table->string('VATrate')->nullable();
            $table->string('grossunit')->nullable();
            $table->string('grosstotal')->nullable();
            $table->timestamps();
            $table->softDeletes();

        );
        
        Schema::table('invoices', function (Blueprint $table)
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');           

          
            $table->foreign('form_id')
                  ->references('id')
                  ->on('forms')
                  ->onDelete('cascade');                
    

            $table->foreign('currency_id')
                  ->references('id')
                  ->on('currencys')
                  ->onDelete('cascade');
 
            
            $table->foreign('proform_id')
                  ->references('id')
                  ->on('proforms')
                  ->onDelete('cascade');

        );
             
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    
        Schema::dropIfExists('invoices');
    

型号:

<?php


namespace App;

use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Invoice extends Model

    /**
     * The attributes that are mass assignable.
     *  
     * @var array
     */
    use SoftDeletes;
    use Sortable;
    
    
    protected $table = 'invoices';

    
    protected $fillable = [
        'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod', 
        'paymentdate', 'status', 'comments', 'city', 'paid',  'autonumber', 'automonth', 'autoyear', 'name',
         'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
         'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
    ];
    
    public $sortable = [ 'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod', 
        'paymentdate', 'status', 'comments', 'city', 'paid',  'autonumber', 'automonth', 'autoyear', 'name',
         'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
         'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
                       ];
    
    protected $dates = ['deleted_at'];
    public $primaryKey = 'id';
    
        public function user()
    
        return $this->belongsTo('App\User');
    

        public function form()
    
        return $this->hasOne('App\Form');
    

         public function currency()
    
        return $this->hasOne('App\Currency');
    
   
        public function proform()
    
        return $this->belongsTo('App\Proform');
     
    

控制器:

<?php
    
namespace App\Http\Controllers;
use Kyslik\ColumnSortable\Sortable;    
use App\Invoice;
use Illuminate\Http\Request;
use App\User;
use App\Proform;
use App\Form;
use App\Currency;
use DB;     
    
class InvoiceController extends Controller
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    
         $this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]);
         $this->middleware('permission:product-create', ['only' => ['create','store']]);
         $this->middleware('permission:product-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:product-delete', ['only' => ['destroy']]);
    
    
    public function search4(Request $request)
    

    $user = User::all('showname','id');
    $invoices = Invoice::sortable()->paginate(5);
        
    $query = DB::table('users')
            ->join('invoices', 'users.id', '=', 'invoices.user_id');
            
        
    $search = $request->get('search');
    $requestData = ['showname'];
        
    /* $query = Proform::query(); */
    foreach ($requestData as $field)
    $query->orWhere($field, 'like', '%'.$search.'%');
    
    $data2=$query->paginate(5);
    return view('invoices.index', ['invoices' => $data2, 'user'=> $user])->with('i', ($request->input('page', 1) - 1) * 5);
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    
        $user = User::all('showname','id');
        $invoices = Invoice::sortable()->paginate(5);
        return view('invoices.index',compact('invoices', 'user'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
       $users = User::all('showname','id');
        $forms = Form::all('id', 'form');
        $currencys = Currency::all('id', 'currency', 'course');
        return view('invoices.create')->with('users', $users, 'forms', 'currencys');
    
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    
        request()->validate([
            'invoicedate' => 'required',
            'user_id' => 'required',
            'selldate' => 'required',
            'paymentdate' => 'required',
            'paymentmethod' => 'required',
            'status' => 'required',
            'comments' => 'nullable',
            'city' => 'nullable',
            'paid' => 'nullable',
            'name' => 'required',
            'PKWIU' => 'nullable',
            'quantity' => 'required',
            'unit' => 'required',
            'netunit' => 'required',
            'nettotal' => 'required',
            'VATrate' => 'required',
            'grossunit' => 'required',
            'grosstotal' => 'required',
            

            
        ]);
        
        

        Invoice::create($request->all());
    
        return redirect()->route('invoices.index')
                        ->with('success','Invoice created successfully.');
    
    
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Invoice $invoice)
    
        return view('invoices.show',compact('invoice'));
    
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Invoice $invoice)
    
        $users = User::all('showname','id');
        $forms = Form::all('id', 'form');
        $currencys = Currency::all('id', 'currency', 'course');
        return view('invoices.edit',compact('invoice', 'users', 'forms', 'currencys'));
    
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Invoice $invoice)
    
         request()->validate([
            'invoicedate' => 'required',
            'user_id' => 'required',
            'selldate' => 'required',
            'paymentdate' => 'required',
            'paymentmethod' => 'required',
            'status' => 'required',
            'comments' => 'nullable',
            'city' => 'nullable',
            'paid' => 'nullable',
            'name' => 'required',
            'PKWIU' => 'nullable',
            'quantity' => 'required',
            'unit' => 'required',
            'netunit' => 'required',
            'nettotal' => 'required',
            'VATrate' => 'required',
            'grossunit' => 'required',
            'grosstotal' => 'required',
        ]);
    
        $invoice->update($request->all());
    
        return redirect()->route('invoices.index')
                        ->with('success','Invoice updated successfully');
    
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Invoice $invoice)
    
        $invoice->delete();
    
        return redirect()->route('invoices.index')
                        ->with('success','Invoice deleted successfully');
    

查看:

@extends('layouts.app')


@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Dodaj nową fakturę</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href=" route('invoices.index') ">Wstecz</a>
            </div>
        </div>
    </div>


    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li> $error </li>
                @endforeach
            </ul>
        </div>
    @endif


    <form action=" route('invoices.store') " method="POST">
        @csrf


         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Data wystawienia:</strong>
                    <input type="text" name="invoicedate"  class="form-control" placeholder="Data wystawienia">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Kontrahent:</strong>
                                        <br>
                    <select class="form-controll" name="user_id">
                            @foreach($users as $user)
                            <option value="$user->id">$user->showname</option>
                            @endforeach
                    </select>
                    <br>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Data sprzedaży:</strong>
                    <input type="text" name="selldate" class="form-control" placeholder="Data sprzedaży">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Termin płatności:</strong>
                    <input type="text" name="paymentdate"  class="form-control" placeholder="Termin płatności">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Forma płatności:</strong>
                    <input type="text" name="paymentmethod" class="form-control" placeholder="Forma płatności">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Miejsce wystawienia:</strong>
                    <input type="text" name="city" class="form-control" placeholder="Miejsce wystawienia">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Wpłacono:</strong>
                    <input type="text" name="paid" class="form-control" placeholder="Wpłacono">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Status:</strong>
                    <input type="text" name="status" class="form-control" placeholder="Status">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Uwagi:</strong>
                    <input type="text" name="comments" class="form-control" placeholder="Uwagi">
                </div>
            </div>
            <div class="pull-left" style="margin: 15px;">
                <h3>Pozycje faktury</h3>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Nazwa towaru lub usługi:</strong>
                    <input type="text" name="name"  class="form-control" placeholder="Data wystawienia">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>PKWiU:</strong>
                    <input type="text" name="PKWIU" class="form-control" placeholder="Kontrahent">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Ilość:</strong>
                    <input type="text" name="quantity" class="form-control" placeholder="Kategoria">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Jednostka:</strong>
                    <input type="text" name="unit"  class="form-control" placeholder="Termin płatności">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Cena netto jednostki:</strong>
                    <input type="text" name="netunit" class="form-control" placeholder="Forma płatności">
                </div>
            </div>
             <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Netto razem:</strong>
                    <input type="text" name="nettotal" class="form-control" placeholder="Forma płatności">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Stawka VAT:</strong>
                    <input type="text" name="VATrate" class="form-control" placeholder="Status">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Brutto jednostka:</strong>
                    <input type="text" name="grossunit" class="form-control" placeholder="Uwagi">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Brutto razem:</strong>
                    <input type="text" name="grosstotal" class="form-control" placeholder="Uwagi">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Zapisz</button>
            </div>
        </div>


    </form>



@endsection

不工作的列是:名称、PKWIU、数量、单位、净单位、净总额、增值税率、毛单位、毛总额。软删除也不行。

dd ($request->all());给了我:

   array:19 [▼
      "_token" => "t5EYPt5CB1zjbqX1VIw7mWqEhukRlnOnvOOnmi9G"
      "invoicedate" => "2020-03-02"
      "user_id" => "1"
      "selldate" => "2020-03-05"
      "paymentdate" => "2020-03-04"
      "paymentmethod" => "Przelew"
      "city" => "Warszawa"
      "paid" => "78"
      "status" => "aktywny"
      "comments" => "Brak"
      "name" => "Piotr"
      "PKWIU" => "hgkk"
      "quantity" => "6"
      "unit" => "76876"
      "netunit" => "7686"
      "nettotal" => "7686"
      "VATrate" => "768"
      "grossunit" => "768"
      "grosstotal" => "687"
    ]

【问题讨论】:

你能把 $request->all() 转储到你的控制器中,看看数量和其他缺失的字段是否至少达到了这一点? 是的,我做到了,所有的值都在里面。 array:19 [▼ "_token" => "t5EYPt5CB1zjbqX1VIw7mWqEhukRlnOnvOOnmi9G" "invoicedate" => "2020-03-02" "user_id" => "1" "selldate" => "2020-03 -05" "paymentdate" => "2020-03-04" "paymentmethod" => "Przelew" "city" => "Warszawa" "paid" => "78" "status" => "aktywny" "cmets" => "Brak" "名称" => "Piotr" "PKWIU" => "hgkk" "数量" => "6" "单位" => "76876" "netunit" => "7686" "nettotal" => "7686" "增值税" => "768" "grossunit" => "768" "grosstotal" => "687" ] 我试过了:composer dump-autoload php artisan view:clear php artisan config:cache php artisan cache:clear 但我没有帮助 您能否迁移:新鲜或确保您有最新的数据库列更改? 【参考方案1】:

将您的控制器方法更改为类似

public function store(Request $request)
    
        $validatedData = request()->validate([
            'invoicedate' => 'required',
            'user_id' => 'required',
            'selldate' => 'required',
            'paymentdate' => 'required',
            'paymentmethod' => 'required',
            'status' => 'required',
            'comments' => 'nullable',
            'city' => 'nullable',
            'paid' => 'nullable',
            'name' => 'required',
            'PKWIU' => 'nullable',
            'quantity' => 'required',
            'unit' => 'required',
            'netunit' => 'required',
            'nettotal' => 'required',
            'VATrate' => 'required',
            'grossunit' => 'required',
            'grosstotal' => 'required',
        ]);
    
        Invoice::create($validatedData);
    
        return redirect()->route('invoices.index')
            ->with('success','Invoice created successfully.');

或换行

Invoice::create($request->all());

Invoice::create($request->only([
    'invoicedate',
    'user_id',
    'selldate',
    'paymentdate',
    'paymentmethod',
    'status',
    'comments',
    'city',
    'paid',
    'name',
    'PKWIU',
    'quantity',
    'unit',
    'netunit',
    'nettotal',
    'VATrate',
    'grossunit',
    'grosstotal',
]));

其中数组是Invoice 模型中fillable 字段的名称。

【讨论】:

之后我看到错误:语法错误,控制器中的公共函数显示(发票 $invoice)中出现意外的“公共”(T_PUBLIC) @PiotrŚwitlicki 我错过了函数右括号。这是一个错字并更新了我的答案。请检查 好的,谢谢。它不返回错误但不工作。在表格中,我在与以前相同的列中有记录。 我假设您在本地/开发服务器上。如果是这样,请在.env 文件中设置APP_ENV=localAPP_DEBUG=trueAPP_LOG_LEVEL=debug,并查看错误消息/错误日志。

以上是关于使用 Laravel 的 Eloquent 向数据库发送数据的问题的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Laravel 中使用 eloquent 检索每个用户的特定数据

Laravel - 向数组添加类属性

Laravel Eloquent 模型 JSON 输出格式

如何使用 eloquent 在 laravel 迁移中删除 POSTGRES 表或视图?

Laravel (Eloquent) 不更新数据库

在 Laravel 中使用 Eloquent 进行更高级的数据库查询