Reputation: 1663
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
Upvotes: 1
Views: 527
Reputation: 8618
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;
});
Upvotes: 1