1

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

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

已经尝试重命名迁移中的方法名、列名,尝试退出 tinker 并重新登录

项目迁移

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();
        });
    }

项目.php

use App\Task;

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

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

任务.php

use App\Project;

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

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

4

1 回答 1

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

// I suggest this
public function project(){
   return $this->belongsTo(Project::class);
}
  • 您的列类型不同,对于您使用 Big Integer 的项目的 id 和您使用 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');
于 2019-06-03T12:10:08.227 回答