[英]How to get any column entry from another table of database based on the entry taken in form?
I am new to laravel and facing an issue.我是 laravel 的新手并面临一个问题。 I have a database and there are two tables named groups and clients.
我有一个数据库,有两个名为组和客户端的表。 I have a form and there are three fields: name, email and group.
我有一个表单,其中包含三个字段:姓名、电子邮件和群组。 The group is dropdown select which is populated by groups entries from the database.
该组是下拉选择,由数据库中的组条目填充。 Now while creating a new client, I want my clients table to have relation with groups table.
现在,在创建新客户端时,我希望我的客户端表与组表有关系。 It will work like this:
它会像这样工作:
Will enter the name, email and will select the group it will associate with.将输入姓名、电子邮件并选择要关联的组。 The 'Client' table will get the id (There is a id column in the database, which is on auto_increament) of the 'Groups' table.
'Client' 表将获得 'Groups' 表的 id(数据库中有一个 id 列,在 auto_increament 上)。
I have created one to one relation and when I put group_id manually in the database, it is showing the respective group.我创建了一对一的关系,当我将 group_id 手动放入数据库时,它显示了相应的组。 But I want the code to get the group_id while creating new entry.
但我希望代码在创建新条目时获取 group_id。
Here is the code which is creating new entry:这是创建新条目的代码:
Student::create([
'name' => request('name'),
'email' => request('email'),
'group_id' => request('group_name')// I want the group Id here,
'user_id' => auth()->user()->id
]);
return back()->with('success', 'The registration is completed');
Here is the form:这是表格:
@extends ('layouts.app')
@section('main')
<div class="col-md-6">
<form method="post" action="/student" class="">
@csrf
<div class="form-group">
<label for="name">Client Name:</label>
<input class="form-control" type="text" name="name" required>
</div>
<div class="form-group">
<label for="email">Client Email:</label>
<input class="form-control" type="text" name="email" required>
</div>
<div class="form-group">
<label for="group_name">Select Group:</label>
<select class="form-control" name="group_name">
@foreach ($groups as $group)
<option>{{ $group->group_name}}</option>
@endforeach
</select>
</div>
<div class="form-group ">
<input class="btn btn-primary" type="submit" name="submit">
</div>
</form>
</div>
@endsection
Here is the error code:这是错误代码:
SQLSTATE[HY000]: General error: 1364 Field 'group_group_name' doesn't have a default value (SQL: insert into `students` (`name`, `email`, `group_id`, `user_id`) values (Nayan Chowdhury, nayan.1aacl@gmail.com, Marketing, 1))
You are doing wrong.你做错了。 Try
尝试
<select class="form-control" name="group_name">
@foreach ($groups as $group)
<option value="{{ $group->id }}">{{ $group->group_name}}</option>
@endforeach
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.