我正在使用 Laravel 8,我有以下非常简单的模型和迁移,
作者模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Author extends Model
{
use HasFactory;
public function profile()
{
return $this->hasOne('App\Models\Profile');
}
}
轮廓模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
use HasFactory;
public function author()
{
$this->belongsTo('App\Models\Author');
}
}
create_authors_table 迁移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAuthorsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('authors');
}
}
create_profiles_table 迁移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('author_id')->unique();
$table->foreign('author_id')->references('id')->on('authors');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
尽管有上述模型和迁移,但如果我Profile
在 tinker shell 中创建一个新模型并执行$profile->author()
它会返回null
. 我不明白问题出在哪里。
(我尝试更改$this->belongsTo('App\Models\Author');
和$this->belongsTo(Author::class);
重新$this->hasOne('App\Models\Profile');
启动$this->hasOne(Profile::class);
修补程序。问题仍然存在。我什至尝试将所有无符号整数键更改为无符号大整数,但问题仍然存在。)