数据库表
jobcategories
id | name
1 | IT
2 | MBA
3 | Pharmacy
我通过在jobdetails表中选择下拉值来保存其中一个值。
jobdetails
id | job_title | jobcategory_id | ...
1 | Software Engg. | 1
// JobDetail model
public function jobcategory()
{
return $this->belongsTo('JobCategory');
}
// JobCategory model
public function jobdetails()
{
return $this->hasMany('JobDetail', 'jobcategories');
}
要保存的控制器
public function postAddJobs() {
$input = Input::all();
if(isset($_POST['submit'])){
$jobdetails = JobDetail::create(array
(
'job_title' => $input['title'],
.........
)
);
}
if(isset($input['category'])){
foreach($input['category'] as $catID){
$jcat = JobCategory::find($catID);
$jobdetails->jobcategory()->associate($jcat);
$jobdetails->save();
}
}
查看我保存的文件
<select name="category[]" class="details">
<option value="">Select Category</option>
@foreach(JobCategory::all() as $jcat)
<option value="{{ $jcat->id }}">{{ $jcat->name }}</option>
@endforeach
</select>
编辑控制器
public function getJobEdit($id)
{
$jobedit = JobDetail::find($id);
$cat = JobCategory::where('id','=',$jobedit->jobcategory_id)->get();
return View::make('employers.edit_single_jobs')->with('jobedit',$jobedit)
->with('cat', $cat);
}
显示编辑数据库的页面
<select name="category[]" class="details">
<option value="">{{ $jobedit->jobcategory->name }}</option>
@foreach(JobCategory::all() as $jcat)
<option value="{{ $jcat->id }}">{{ $jcat->name }}</option>
@endforeach
我的问题是,它成功保存并成功编辑但是当我编辑时,数据库中选定的值在选项值中显示两次,为什么它在下拉选项值中显示两次?如果这个保存和编辑过程不完美,请帮我展示保存和编辑的好过程。请帮助,我是学习laravel的新手..