【发布时间】:2025-12-06 19:15:01
【问题描述】:
我有一个记录联系人(姓名、地址等)的简单数据库应用程序。我正在尝试利用其他各种表格来为表格生成值列表。然后我想让用户输入的所有表单值在提交时保存到适当的表中。
例如,我有一个包含姓名和地址的people 表。我有一个title 表,其中包含标题的不同可能值(即先生、夫人、博士女士)。填写联系表格后,我想从标题表中生成表格中标题字段的值。我正在尝试为联系人做这个模型,其中包括人员表和标题表的单独类。
在我的 ContactController.php 中有:
class ContactController extends Controller {
public function index()
{
$people = Contact::all();
// return main homepage for Contacts section
return view('pages.contacts.home', compact('people'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
$title = Contact::lists('title', 'id');
return view('pages.contacts.create');
}
在我的 Contact.php 模型中,我有以下内容:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model {
protected $table = 'people';
protected $fillable = [
'title_id',
'name_first',
'name_middle',
'name_last',
'date_birth',
'date_death',
'bio',
'created_at',
'modified_at'
];
public function title() {
return $this->belongsTo('Title', 'title_id', 'id');
}
}
class Title extends Model {
protected $table = 'title';
protected $fillable = [
'title',
'created_at',
'modified_at'
];
public function contacts() {
return $this->hasMany('Contact', 'title_id', 'id');
}
}
在表格中我有以下内容:
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::select('title', $title) !!}
</div>
<div class="form-group">
{!! Form::label('name_first', 'First Name: ') !!}
{!! Form::text('name_first', null, ['class' => 'form-control']) !!}
{!! Form::label('name_middle', 'Middle Name: ') !!}
{!! Form::text('name_middle', null, ['class' => 'form-control']) !!}
{!! Form::label('name_last', 'Last Name: ') !!}
{!! Form::text('name_last', null, ['class' => 'form-control']) !!}
{!! Form::label('name_nick', 'Nickname: ') !!}
{!! Form::text('name_nick', null, ['class' => 'form-control']) !!}
</div>
我收到一条错误消息,指出变量 title 未定义。我无法确定为什么没有返回值列表。我的关系是否返回错误?
【问题讨论】:
标签: laravel eloquent laravel-5