tinker中的以下代码返回一个null值,同时它应该返回第一个任务链接到的项目。
AppTask::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();
});
}
项目.php
use AppTask;
class Project extends Model
{
protected $fillable = ['title','description'];
public function tasks(){
return $this->hasMany(Task::class);
}
}
任务.php
use AppProject;
class Task extends Model
{
protected $fillable = [
'completed'
];
public function projects(){
return $this->belongsTo(Project::class);
}
}
如果有人可以查看这段代码并让我知道我在哪里犯了任何常规\愚蠢的错误(因为我是路由模型绑定的新手),那将有很大帮助!
- 任务属于项目,因此将项目重命名为项目,因为它是单数。如果保留项目,则提供列名作为第二个参数:
public function projects(){
return $this->belongsTo(Project::class, 'project_id');
}
// I suggest this
public function project(){
return $this->belongsTo(Project::class);
}
- 您的列类型不同,对于项目的 id,您使用 Big Integer,对于引用,您使用 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');