Laravel:如何将属性追加到数组

时间:2015-11-30 07:35:21

标签: php arrays json laravel

我有一个从show方法返回的数组。这是show方法:

public function show($id)
{
    $track = Fuelconsumption::where('id', $id)->first();

    return $track;
}

返回:

{
    id: 6,
    distance: 178.6,
    volume: 14.31,
    price: 1.45,
    date: "2015-11-08 14:13:56",
    created_at: "2015-11-30 03:29:57",
    updated_at: "2015-11-30 03:29:57"
}

我想从提供的值中进行一些计算(平均值等),并将这些变量附加到json数组上面。

现在我正在通过在新new Kpi中创建KpiController对象来解决问题。控制器将上面的array(这是一个FuelConsumption对象)传递给我的constructor

这是show的{​​{1}}方法:

KpiController
我的public function show($id) { $item = Fuelconsumption::where('id', $id)->first(); $kpi = new Kpi($item); return $kpi['list']; } 课程的

Constructor

Kpi

它返回一个如下所示的Json数组:

protected $avgFuel;
protected $avgCost;
protected $cost;
protected $list;

/**
 * Creates all necessary KPIs
 * 
 * @param Object $item Fuelconsumption
 */
public function __construct(Fuelconsumption $item)
{
    $this->avgFuel = $this->avgFuelperUnitofDistance($item);
    $this->avgCost = $this->avgCostPerUnitOfDistance($item);
    $this->cost = $this->cost($item);

    $this->list = [
        'avgFuelperUnitOfDistance' => $this->avgFuel, 
        'avgCostperUnitOfDistance' => $this->avgCost,
        'cost' => $this->cost
    ];
}

我现在遇到的问题是当我访问以下URI时返回第一个数组:

{
     avgFuelperUnitOfDistance: 0.08,
     avgCostperUnitOfDistance: 0.116,
     cost: 20.75
}

访问此URI时会返回第二个数组:

http://localhost:8000/fuelconsumption/6

问题在于我希望将两个Json Arrays组合在一个数组中,我不知道如何实现这一点。

这是我的想法:

修改Fuelconsumption类

将我的FuelConsumptionController修改为:

http://localhost:8000/fuelconsumption/6/kpi

我的public function show($id) { $item = Fuelconsumption::where('id', $id)->first(); $kpi = new Fuelconsumption($item); dd($kpi); } 课程中有一个构造函数:

Fuelconsumption

不幸的是,这引发了错误:

  

缺少App \ Fuelconsumption :: __ construct()

的参数1

在我的理解中,因为即使在我第二次在控制器中回忆它之前,该类也被调用了。不知道如何解决这个问题。

第二个想法:扩展KPI对象

要包含我想要的所有其他变量,然后以某种方式返回我的FuelConsumptionController @ show方法中的完整数组。

第三个想法:以某种方式组合这些数组

不确定如何。

现在我认为最简单的解决方案是扩展KPI模型(我的第二个想法),但我希望通过某种方式将class Fuelconsumption extends Model { protected $fillable = ['distance', 'volume', 'price', 'date']; protected $dates = ['date']; protected $cost; public function __construct($item) { $this->cost = $this->cost($item); } public function cost($item) { return round($item->volume * $item->price, 2); } } 传递给我{{1}来完全摆脱KPI类构造函数。

2 个答案:

答案 0 :(得分:2)

你几乎是正确的...因为你的班级<h1>${fizz}</h1>是一个雄辩的模型,FuelConsumption已经由Laravel设置并且你试图覆盖它。

Eloquent所做的是使用__construct->first()返回单个模型(就像你拥有的那样)。使用->find($id)->all()时,它会返回一个Eloquent Collection。

可行的方法:

->get()

你的api控制器方法可能如下:

class Fuelconsumption extends Model
{
    protected $fillable = ['distance', 'volume', 'price', 'date'];

    protected $dates = ['date'];

    protected $cost;

    public function cost() {
        return round($this->volume * $this->price, 2);
    }

    public function avgFuelperUnitofDistance() {
        return $this->distance / $volume; // do your thing, dummy calc
    }

    public function avgCostPerUnitOfDistance() {
        return $this->distance / $price;  // do your thing, dummy calc
    }
}

或者如果你真的想要创建和合并属性:

public function show($id)
{
    $item = Fuelconsumption::find($id)->first();
    // if $item == null if it is item was not found
    if (!$item) {
        return response('item was missing', 404);
    }

    // $item will look like:
    // class Fuelconsumption: {
    //    id: 6,
    //    distance: 178.6,
    //    volume: 14.31,
    //    price: 1.45,
    //    date: "2015-11-08 14:13:56",
    //    created_at: "2015-11-30 03:29:57",
    //    updated_at: "2015-11-30 03:29:57"
    // }

    // doing more stuff over here

    // create the json response
    return response()->json([
        'id' => $item->id,
        'distance' => $item->distance,
        'volume' => $item->volume,
        'price' => $item->price,
        'date' => $item->date,
        'cost' => $item->cost(),
        'avg_fuel' => $item->avgFuelperUnitofDistance(),
        'avg_unit' => $item->avgCostperUnitofDistance(),
    ]);
}

答案 1 :(得分:1)

解决问题的另一种方法是用户naneri建议使用此链接:

http://laravel.com/docs/5.1/eloquent-serialization#appending-values-to-json

然后我的模型看起来像这样:

class Fuelconsumption extends Model
{
    protected $fillable = ['distance', 'volume', 'price', 'date'];

    protected $dates = ['date'];

    protected $appends = ['cost', 'avg_fuel_per_unit_of_distance', 'avg_cost_per_unit_of_distance'];

    public function getCostAttribute()
    {
        return round($this->attributes['volume'] * $this->attributes['price'], 2);
    }

    public function getAvgFuelPerUnitOfDistanceAttribute()
    {
        return round($this->attributes['volume'] / $this->attributes['distance'], 3 );
    }

    public function getAvgCostPerUnitOfDistanceAttribute()
    {
        return round($this->attributes['volume'] * $this->attributes['price'] / $this->attributes['distance'], 3);
    }

}

获取URI show

时,http://localhost:8000/fuelconsumption/6方法的输出会如下所示
{
    id: 6,
    distance: 178.6,
    volume: 14.31,
    price: 1.45,
    date: "2015-11-08 14:13:56",
    created_at: "2015-11-30 03:29:57",
    updated_at: "2015-11-30 03:29:57",
    cost: 20.75,
    avg_fuel_per_unit_of_distance: 0.08,
    avg_cost_per_unit_of_distance: 0.116
}