当我尝试在 Invoice table 上添加外键时,为什么会出现此错误?

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

我有两个表 usersinvoices。这是 users 迁移的 up 函数:

public function up()
{
    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();
    });
}

这是 invoices 迁移的 up 函数:

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();
    });
}

我想做的就是建立一个一对多的关系,因为一个用户可以有多个发票。

这里是 User 模型:

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);
    }
}

这里是 Invoice 模型:

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')

更多关于Available Column Types

您有两个问题:

  1. 您的迁移声明中有错字

  2. $this->id() 使 unsignedBigInteger 所以 user_id 应该是 unsignedBigInteger

将您的迁移行更改为:

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