【问题标题】:foreign key not define in migration file in Laravel 5.2Laravel 5.2 的迁移文件中未定义外键
【发布时间】:2017-08-20 06:12:21
【问题描述】:

我的 laravel 应用中有两个迁移文件作为项目和任务。项目 id 列是任务表 project_id 的外键。我需要在任务表中将项目 ID 保存为 project_id。但我没有在我的任务迁移文件中配置外键关系 任务迁移文件

public function up()
    {
         Schema::create('tasks', function(Blueprint $table)
        {
            $table->increments('id')->unsigned();
            $table->longText('task_name');
            $table->text('body');
            $table->string('assign');
            $table->string('priority');
            $table->date('duedate');
            $table->integer('project_id')->unsigned();
            $table->timestamps();
 });

    }

这是我的任务控制器

public function postNewTask(Request $request, Project $project)
{
    $task = new Task;
    $task->task_name   = $request->input('name');
    $task->body = $request->input('body');
    $task->assign = $request->input('status');
    $task->priority = $request->input('status');
     $task->duedate  = date("Y-m-d", strtotime($request->input("date")));
     $task->project_id = $project->id;

   // This will set the project_id on task and save it
    $project->tasks()->save($task);

}

任务模型

class Task extends Model
{
     protected $fillable = ['task_name', 'body', 'assign','priority','duedate','project_id'];

public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }


     public function project()
     {
         return $this->belongsTo('App\Project');
     }

项目模型

class Project extends Model
{
    protected $fillable = ['project_name','project_notes','project_status','color','group'];
    //

    public function tasks(){
         return $this->hasMany('App\Task');

我的表单操作

<form  method="post" action="{{ route('projects.tasks.create', $project->id) }}">

和路线

Route::post('projects/{projects}/tasks', [
    'uses' => '\App\Http\Controllers\TasksController@postNewTask',
    'as' => 'projects.tasks.create'
]);

但是当我要保存表单数据时出现以下错误消息

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'project_id' cannot be null

如何解决这个问题。这是我的迁移文件外键没有定义问题吗?

【问题讨论】:

    标签: php mysql laravel-5


    【解决方案1】:

    终于得到了和这个TaskController一样的结果

      public function postNewTask(Request $request,$id, Project $project)
        {
    
            $task = new Task;
            $task->task_name   = $request->input('name');
            $task->body = $request->input('body');
            $task->assign = $request->input('status');
            $task->priority = $request->input('status');
            $task->duedate  = date("Y-m-d", strtotime($request->input("date")));
            $task->project_id = $id;
            $task->save();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 2016-06-24
      • 2021-12-31
      • 2020-06-05
      • 2016-05-13
      • 2023-01-04
      • 2016-12-16
      • 2016-11-20
      • 2019-09-23
      相关资源
      最近更新 更多