首页 > 解决方案 > 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

标签: laraveleloquent

解决方案


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;
});

推荐阅读