laravel关系未显示外键值

时间:2019-03-14 21:42:43

标签: laravel eloquent

我已经在两个表之间创建了一个关系,但是当我调用它时显示的是 id 而不是外键

我的单位模型:

class Unit extends Model
{
   protected $table='units';
   public function unit_id()
   {
       return $this->hasMany(Procurment_request::class,'unit_id','id');
   }
}

我的采购模型:

class Procurment_request extends Model
{
    protected $table ='procurment_requests';
    public function unit_id(){
        return $this->belongsTo(App\Unit::class);
    }
}

我的路线:

Route::get('show',function (){
    $result=Procurment_request::all();
    return $result;
});

结果:

[  
   {  
      "id":1,
      "quantity":1,
      ***"units_id":1***,
      "description":"adf",
      "requster":0,
      "checker":0,
      "approver":0,
      "created_at":null,
      "updated_at":null
   }
]

我想显示单位名称而不是主键

1 个答案:

答案 0 :(得分:1)

将关系名称更改为

class Procurment_request extends Model
{
    protected $table ='procurment_requests';

    public function unit(){
        return $this->belongsTo(App\Unit::class, 'units_id');
    }

}

并使用

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