我有一张表格:
<label for="task-name" class="col-sm-3 control-label">Task</label>
<div class="col-sm-6">
<input type="text" name="name" id="task-name" class="form-control">
</div>
</div>
<input name="project_id" id="task-project_id" type="hidden" value="{{ $project->id }}">
一种存储两个表单字段的方法:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'project_id' => 'required',
]);
Task::create([
'project_id' => $request->project_id,
'name' => $request->name,
]);
return redirect()->back();;
}
但是,只有'name'保存到db表。任务表有两个列名和&amp;虽然我可以回复正确的$request->project_id
回来(以测试它通过),但保存的project_id
总是为'0'。
这是表格:
mysql> explain tasks;
+------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | project_id | int(11) | NO | MUL | NULL | | | name | varchar(255) | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+
也手动检查了创建:
App\Task::create(['project_id' => 20,'name' =>'testtt']);
输出:
App\Task {
name: "testtt",
updated_at: "2016-07-29 01:08:09",
created_at: "2016-07-29 01:08:09",
id: 25
}
感谢。
答案 0 :(得分:1)
我在返回的任务对象中根本看不到project_id
属性:
App\Task {
name: "testtt",
updated_at: "2016-07-29 01:08:09",
created_at: "2016-07-29 01:08:09",
id: 25
}
这意味着您不允许project_id
数组中的Task
模型中的$fillable
属性,因此请确保您的$fillable
看起来像:< / p>
protected $fillable = ['name', 'project_id'];
希望这有帮助。
答案 1 :(得分:1)
Ahhhhhhhhh
class Task extends Model
{
protected $fillable = ['name', 'project_id'];
public function tasks()
{
return $this->belongsTo(Project::Class);
}
}
需要将project_id添加到任务模型中的$ fillable。
答案 2 :(得分:0)
确保:
$project->id
已设置且高于0. $request->project_id
已设置且高于0. project_id
已存在。告诉我,如果你在这三点上遇到任何麻烦,我会尽力帮助你,但我真的认为通过检查你的代码中的这三点,你会发现错误!尝试使用函数var_dump($var)
和浏览器检查器来检查是否正确设置了所有变量。
答案 3 :(得分:0)
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'project_id' => 'required',
]);
$task = new Task;
$task->project_id = $request->project_id;
$task->name = $request->name;
$task->save();
return redirect()->back();;
}
参考:https://laravel.com/docs/5.1/eloquent#inserting-and-updating-models