0

我正在使用 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);修补程序。问题仍然存在。我什至尝试将所有无符号整数键更改为无符号大整数,但问题仍然存在。)

4

2 回答 2

0

所以我发现了问题所在。解决方案很简单,我忘记在模型内部的方法中添加所有重要return的语句。author()Profile

应该是, return $this->belongsTo('App\Models\Author');而不是$this->belongsTo('App\Models\Author');

于 2021-10-03T04:36:11.340 回答
0

试试这个 return $this->belongsTo(Author::class, 'author_id', 'id'); 而不是 $this->belongsTo('App\Models\Author');

于 2021-10-03T04:36:12.323 回答