php - Laravel 7关系查询数据不起作用
问题描述
我想通过员工查询公司名称。为什么没有得到任何结果?它不会给出任何错误。
公司模式
public function employees() {
return $this->hasMany(Employees::class);
}
员工模型
public function companies() {
return $this->belongsTo(Companies::class);
}
员工控制器
public function createIndex() {
$employees = Employees::all();
return view('employees.create', [
'employees' => $employees
]);
}
我想查询的地方
<div class="form-group">
<label for="company">Company: </label>
<select name="company" class="form-control">
@foreach($employees as $employe)
<option selected>Choose...</option>
@foreach($employe->companies as $company)
<option id="company">{{ $company->name }}</option>
@endforeach
@endforeach
</select>
</div>
这是表的迁移
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email');
$table->string('logo');
$table->string('website');
$table->timestamps();
});
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('fname');
$table->string('lname');
$table->string('email');
$table->string('phone');
$table->bigInteger('companies_id')->unsigned();
$table->timestamps();
$table->foreign('companies_id')->references('id')->on('companies')
->onDelete('cascade');
});
解决方案
请提供您关系的外键...
public function companies()
{ return $this->belongsTo(Companies::class,'companies_id'); }
这种关系意味着该员工只有一家公司(属于一家公司)
所以你不能迭代它!
在这一行:
@foreach($employe->companies as $company)
<option id="company">{{ $company->name }}</option>
@endforeach
employee->companies 将只返回一个对象.. 如果您想将所有公司显示为选项,请传递 $allCompany ,例如:
public function createIndex() {
$employees = Employees::all();
$compnanies = Companies::all();
return view('employees.create', [
'employees' => $employees,'compnanies'=> $compnanies
]);
}
然后你可以在你的视图中迭代 $compnanies
推荐阅读
- installation - cd 找不到/打开 ~/.vim/bundle/YouCompleteMe
- r - 代码运行良好,但显示错误闪亮
- javascript - 将图像动态加载到覆盖的画布中并调整它们的大小
- python - 在 Python 中的 MIP 求解器或工具的约束中使用 If else 语句
- python - 在编写用于在一个列表中转换两个列表的代码时,我在 python 中遇到此错误“并非所有参数都在字符串格式化期间转换”
- python - 用于 ETL 的管道 python 脚本
- dart - Dart 语言中的 ^ 运算符是什么?
- camera - Raspberry Pi 上的运动:USB 4 通道复合视频捕获设备上的 2 个摄像头出现问题
- typescript - 将范围映射到值的最佳数据结构是什么?
- java - Android 11 上 createDeleteRequest() 的 OnActivtyResult