使用多个模型返回JSON响应

时间:2016-03-07 12:29:57

标签: mysql laravel-5.1

我正在尝试返回一个JSON响应,该响应由一系列帐户组成,其中每个帐户都有一种货币(名称,费率)。

到目前为止我得到了什么:

http:{server instance}/context-path/customers

但我需要的是:

[
  {
    id: 10001,
    currency_id: 1,
    amount: 11000,
    currency: {
      id: 1,
      name: "Dollar",
      rate: 5.1
    }
  }
]

currency.php模型:

[
  {
    id: 10001,
    currency: {
      id: 1,
      name: "Dollar",
      rate: 5.1
    },
    amount: 11000,
  }
]

account.php模型:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class currency extends Model {

    protected $fillable = array('name', 'rate');

    public function account(){
        return $this->hasOne('App\account', 'account');
    }
}

和我的AccountController:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class account extends Model {

    protected $fillable = array('client_id', 'currency_id', 'branch_id', 'credit', 'debit', 'type');

    public function currency()
    {
        return $this->belongsTo('App\currency');
    }
}

1 个答案:

答案 0 :(得分:1)

如果您只想隐藏currency_id,可以使用$hidden模型上的account属性,如此

protected $hidden = ['currency_id'];

请参阅此处的文档https://laravel.com/docs/5.1/eloquent-serialization#hiding-attributes-from-json