【发布时间】: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
如何解决这个问题。这是我的迁移文件外键没有定义问题吗?
【问题讨论】: