我必須表:用戶和發票 這是用戶遷移的 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();
});
}
這是發票的 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();
});
}
我想要做的就是建立一對多的關系,因為用戶可以有多個發票
這是用戶模型:
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);
}
}
這是發票模型:
<?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);
}
}
我究竟做錯了什么?我已經看過多個教程了..這里是我得到的錯誤:
錯誤
uj5u.com熱心網友回復:
列需要是相同的型別。id()是 的別名bigIncrements(),所以
$table->unsignedInteger('user_id');
應該
$table->unsignedBigInteger('user_id');
另請注意:它是->references('id'),不是->refferences('id')
有關可用列型別的更多資訊
uj5u.com熱心網友回復:
你有兩個問題:
1-您的遷移宣告中有一個錯字
2-$this->id()做出unsignedBigInteger這樣user_id應該是unsignedBigInteger
將您的遷移行更改為:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users'); //references not refferences
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361343.html
