簡體   English   中英

當我嘗試在 Invoice 表上添加外鍵時,為什么會出現此錯誤?

[英]Why am i getting this error when i try to add foreign keys on Invoice table?

我必須表:用戶和發票這是用戶遷移的 function:

    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('email')->unique();
            $table->string('phone')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('comentarii');

            $table->rememberToken();
            $table->timestamps();
        });
    }

這是發票的 function

 public function up()
    {
        Schema::create('invoices', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->refferences('id')->on('users');
            $table->integer('InvoiceNumber');
            $table->dateTime('date');
            $table->string('serviceInvoiced');
            
            $table->timestamps();
        });
    }

我要做的就是建立一對多的關系,因為用戶可以有多個發票

這是用戶 model:


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\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $guarded = [];

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

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

    public function getInvoices()
    {
        return $this->hasMany(Invoice::class);
    }
}

這是發票 model:

<?php

namespace App\Models;

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

class Invoice extends Model
{
    use HasFactory;

    protected $guarded=[];

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

我究竟做錯了什么? 我已經看了多個教程..這是我得到的錯誤:

錯誤

列必須是相同的類型。 id()bigIncrements()的別名,所以

$table->unsignedInteger('user_id');

應該

$table->unsignedBigInteger('user_id'); 

另請注意:它是->references('id') ,而不是->refferences('id')

有關 可用列類型的更多信息

你有兩個問題:

1-您的遷移聲明中有錯字

2- $this->id()使unsignedBigInteger所以user_id應該是unsignedBigInteger

將您的遷移行更改為:

 $table->unsignedBigInteger('user_id');
 $table->foreign('user_id')->references('id')->on('users'); //references not refferences 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM