【问题标题】:General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `products`..... in laravel-8一般错误:1364 字段“user_id”没有默认值(SQL:在 laravel-8 中插入 `products`.....
【发布时间】:2021-08-11 15:26:05
【问题描述】:

我面临的一个问题是 SQLSTATE[HY000]: 一般错误: 1364 Field 'user_id' doesn't have a default value (SQL: insert into products (name, detail, color, logo, image, updated_at, created_at) 值 (fdsf, sdf, #7536d3, 20210522184540.jpg, 20210522184540.JPG, 2021-05-22 18:45:40, 28-50-22 :45:40))。我希望用户有很多产品 这是我的 ProductController.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(20);

        return view('products.index',compact('products'))

            ->with('i', (request()->input('page', 5) - 1) * 5);
    }

    function authapi(Request $request)
    {
        $user = User:: where('email', $request->email)->first();
        if(!$user || !Hash::check($request->password, $user->password)){
            return response([
                'message' => ['These credentials do not match our records.']
            ],404);
        }

        $token = $user -> createToken('my-app-token')->plainTextToken;

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response,201);
    }

    function all_app_jsons(){
        return Product::all();
    }

    function search_by_name($name){
        return Product::where('name','like','%'.$name.'%')->get();
    }

    function search_by_id($id){
        return Product::where('id',$id)->get();
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //$tag = Product::create($request->all());

        //return redirect()->route('admin.tags.index');
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
        ]);

        $input = $request->all();

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }

        Product::create($input);

        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required'
        ]);

        $input = $request->all();

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }else{
            unset($input['image']);
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }else{
            unset($input['logo']);
        }

        $product->update($input);

        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }

    // function indextwo(){
    //     //return DB::select("select * from  products");
    //    //DB::table('products')->orderBy('id','desc')->first();
    //    return Product::orderBy('id', 'DESC')->first();
    // }

}

这是我的模型product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'detail', 'image','color','logo'
    ];

    public function user(){
        return $this->belongsTo(User::class);
    }
}

这里是模型 user.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];

    public function products(){
        return $this->hasMany(Product::class);
    }
}

这是产品表

  public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->string('color');
            $table->string('image');
            $table->string('logo');
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
        });
        Schema::table('products', function (Blueprint $table){
            $table->foreign('user_id')->references('id')->on('users');

        });
    }

【问题讨论】:

  • 您在创建 Product 时缺少 $input 变量中的 'user_id' 字段。由于您没有在产品迁移中将-&gt;nullable() 添加到user_id,因此是必需的。

标签: laravel laravel-8


【解决方案1】:

我正在使用 Laravel 8 并通过以下两个步骤修复了此错误:

  1. 在用户模式下将单词从$guarded 数组移动到$fillable 数组。 您可以将user_id 放入$fillable 数组中。

    Product 
    {
        fillable=[
            'user_id',
            ... // other attributes
        ];
    }
    

    或者

    Product 
    {
        guarded = [];
    }
    
  2. Config.database.php:'strict' =&gt; false'mysql'的数组中

注意:如果您的问题没有解决,请在您的产品迁移中将user_id 设为nullable

【讨论】:

    【解决方案2】:

    您需要在插入数据时指定带有 id 的用户

    $data['user_id']=$user->id;
    

    或者在数据库中将您的列 user_id 设为 Nullable。

    【讨论】:

      【解决方案3】:

      在这种情况下,您必须将 user_id 添加到 Product Model 的 $fillable 属性中。像这样:

      protected $fillable = [
          'name', 'detail', 'image','color','logo','user_id'
      ];
      

      完成...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 2019-01-05
        • 2021-09-10
        • 1970-01-01
        • 2020-05-25
        • 2017-11-10
        • 2020-04-14
        相关资源
        最近更新 更多