我的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();
});
}
这是我的TaskController
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
如何解决这个问题。这是我的迁移文件外键未定义问题吗?
最佳答案
终于得到了像TaskTask这样的结果
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();
}
关于php - Laravel 5.2的迁移文件中未定义外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45779044/