![](/img/trans.png)
[英]SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")
[英]Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "contacts" does not exist
我的代碼是用 PHP 編寫的,使用 Laravel 和 Postgresql 作為數據庫。
我有一個模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use HasFactory;
protected $fillable = [
'last_name',
'first_name',
'phone_number',
'address',
];
//protected $table = 'database.contact';
protected $hidden = [
'remember_token',
];
}
和遷移:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Contact extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contact ',function(Blueprint $table){
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->integer('phone_number');
$table->ipAddress('address')->nullable();
$table->rememberToken();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contact');
}
}
但是當我在終端運行時:
php artisan tinker
然后:
Contact::create(['last_name' => 'joe', 'first_name' => 'ajoe.com', 'phone_number' => 88552])
我得到錯誤:
Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: relationship "contacts" does not exist LINE 1: insert into "contacts" ("last_name", "first_name", "phone_nu ... ^ ( SQL:插入“聯系人”(“last_name”、“first_name”、“phone_number”、“updated_at”、“created_at”)值(joe, ajoe.com, 88552, 2021-11-06 21:00:43, 2021 -11-06 21:00:43) 返回 "id")'
如果您知道為什么會發生這種情況,我很想得到它謝謝。
在模型中添加這一行
protected $table = 'contact';
第一步:從遷移中的表名中刪除多余的空格:
Schema::create('contact ',function(Blueprint $table){
至:
Schema::create('contact',function(Blueprint $table){
然后,在您的聯系人模型中,設置 $table 屬性:
class Contact extends Model
{
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
protected $table = 'contact';
將此行添加到您的模型protected $table = 'contact';
或改變這個
Schema::create('contact',function(Blueprint $table){
至
Schema::create('contacts',function(Blueprint $table){
並再次migrate:fresh
。 您可以丟失數據,因此第一個使用起來更安全。 但理想的表名應該是contacts
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.