【问题标题】:App\Tasks::first()->projects; in artisan tinker returns null, no matter what :(应用\任务::first()->项目;在工匠修补匠返回null,无论如何:(
【发布时间】:2019-06-03 12:03:27
【问题描述】:

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

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

【问题讨论】:

    标签: php laravel eloquent eloquent-relationship


    【解决方案1】:
    • 任务属于一个项目,因此将项目重命名为项目,因为它是单数的。如果您保留项目,则提供列名作为第二个参数:
    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');
    

    【讨论】:

      猜你喜欢
      • 2017-05-26
      • 2019-03-05
      • 2018-06-26
      • 2023-03-17
      • 1970-01-01
      • 2014-07-01
      • 2016-03-17
      • 2017-08-25
      • 2021-03-29
      相关资源
      最近更新 更多