我有一个使用Laravel Endpoint和Angular7 Frontend的结果管理系统。我想在结果视图中显示exam_name而不是Id。同样,在结果创建视图中,我想显示一个exam_name的下拉列表,并从检查表中保存其ID(值而不是键)。
我已经开发了这两个表:
考试:ID,考试名称,用户ID 结果:id,exam_id,user_id,分数。
考试模型
protected $fillable = [
'exam_name' ,
'user_id'
];
protected $guarded = [
'id'
];
public function user() {
return $this->belongsTo('App\User');
}
public function results()
{
return $this->hasMany(App\Result);
}
结果模型
protected $fillable = [
'score',
'exam_id',
'user_id'
];
protected $guarded = [
'id'
];
public function exam() {
return $this->belongsTo('App\Exam');
}
public function user() {
return $this->belongsTo('App\User');
}
结果:Laravel端点
public function index()
{
$results = Result::all();
return response()->json($results);
}
public function store(Request $request)
{
$request->validate([
'score' => 'required',
'exam_id' => 'required',
]);
$result = Result::create($request->all());
return response()->json([
'message' => 'Great success! New Score created',
'result' => $result
]);
}
public function show(Result $result)
{
return $result;
}
角度:result.service.ts
const apiUrl = "http://localhost/schoolbackend/public/api/results";
getResults (): Observable<Result[]> {
return this.http.get<Result[]>(apiUrl)
.pipe(
tap(results => console.log('Fetch results')),
catchError(this.handleError('getResults', []))
);
}
addResult (result): Observable<Result> {
return this.http.post<Result>(apiUrl, result, httpOptions).pipe(
tap((result: Result) => console.log(`added result w/ id=${result._id}`)),
catchError(this.handleError<Result>('addResult'))
);
}
result-display.component.ts
ngOnInit() {
this.api.getResults()
.subscribe(res => {
this.data = res;
console.log(this.data);
this.isLoadingResults = false;
}, err => {
console.log(err);
this.isLoadingResults = false;
});
}
result-add.component.ts
onFormSubmit(form:NgForm) {
this.isLoadingResults = true;
this.api.addResult(form)
.subscribe(res => {
// let id = res['_id'];
this.isLoadingResults = false;
this.router.navigate(['/resultlist']);
}, (err) => {
console.log(err);
this.isLoadingResults = false;
});
}
result-display.component.html
<tr *ngFor="let datas of data">
<td>{{datas.score}}</td>
<td>{{datas.exam_id}}</td>
<td>
result-add.component.html
<input type="text" class="form-control" formControlName="score" name="score" id="score">
<input type="text" class="form-control" formControlName="exam_id" name="exam_id" id="exam_id">
result-display.component.html
我要显示的是exam_name(这是来自考试表)而不是exam_id。 2.也在
result-add.component.html
应该是一个下拉菜单,用于显示而不是exam_id(来自考试表)的exam_name。还应将id(exam_id)而不是value(exam_name)保存到结果表中