App\Tasks::first()->项目; in artisan tinker returns null,无论如何:(

App\Tasks::first()->projects; in artisan tinker returns null, no matter what :(

tinker 中的以下代码 return 是一个空值,而它应该 return 第一个任务链接到的项目。

App\Task::first()->projects;

已经尝试重命名迁移中的方法名称、列名称,尝试退出修补程序并重新登录

项目迁移

public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('title');
            $table->string('description');
            $table->timestamps();
        });
    }

任务迁移

public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('project_id');
            $table->string('description');
            $table->boolean('completed')->default(false);
            $table->timestamps();
        });
    }

Project.php

use App\Task;

class Project extends Model
{
    protected $fillable = ['title','description'];

    public function tasks(){
      return $this->hasMany(Task::class);
    }
}

Task.php

use App\Project;

class Task extends Model
{
  protected $fillable = [
    'completed'
  ];
  public function projects(){
    return $this->belongsTo(Project::class);
  }
}

如果有人可以查看这段代码并让我知道我在哪里犯了任何 conventional\idiotic 错误(因为我是路由模型绑定的新手),那将会很有帮助!

  • 一个任务属于一个项目,所以将projects重命名为project,因为它是单数的。如果您保留项目,则提供列名称作为第二个参数:
public function projects(){
   return $this->belongsTo(Project::class, 'project_id');
}

// I suggest this
public function project(){
   return $this->belongsTo(Project::class);
}
  • 你的column类型不一样,project的id用的是Big Integer,reference用的是Integer,所以:
$table->unsignedInteger('project_id');

应该是这样的:

$table->unsignedBigInteger('project_id');

// also good to make the relationship on the Database level:

$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');