laravel - laravel relationship not showing foreign key value
问题描述
I've created a relationship between two tables but when I call it shows the id instead of foreign key
My Unit model:
class Unit extends Model
{
protected $table='units';
public function unit_id()
{
return $this->hasMany(Procurment_request::class,'unit_id','id');
}
}
My Procurment Model:
class Procurment_request extends Model
{
protected $table ='procurment_requests';
public function unit_id(){
return $this->belongsTo(App\Unit::class);
}
}
My Route:
Route::get('show',function (){
$result=Procurment_request::all();
return $result;
});
And the result:
[
{
"id":1,
"quantity":1,
***"units_id":1***,
"description":"adf",
"requster":0,
"checker":0,
"approver":0,
"created_at":null,
"updated_at":null
}
]
I want to show the name of Unit not the primary key
解决方案
Change relation name to
class Procurment_request extends Model
{
protected $table ='procurment_requests';
public function unit(){
return $this->belongsTo(App\Unit::class, 'units_id');
}
}
And use
Route::get('show',function (){
$result=Procurment_request::with('unit')->get();
$result->map(function ($item) {
$item->unit_name = $item->unit->unit_name;
unset($item['unit']);
});
return $result;
});
推荐阅读
- javascript - 与 angular6 中 *ngFor 中的多个 mat-table 相关的问题
- php - Yii2登录后角色切换
- api - 有什么方法可以确保最新 wso2ei 6.4.0 中部署的 REST 服务的基本身份验证?
- arrays - 如何从 O(logn) 复杂度的未排序数组中删除?
- encryption - 从十六进制和 LRC 解码数据
- r - 如果我在不同情况下需要不同的结尾,如何构造一个 for 循环?
- vb.net - 删除 PowerPoint 幻灯片标题
- ios - 使用 Siri 快捷方式为一项特定任务注册多个短语
- python - GCP 部署管理器 - 删除防火墙规则(如果存在)
- django - 在 ModelAdmin.readonly_fields 方法中使用模板标签