I have been looking all around the internet but there does not appear to be much in this issue.
In short I have a Model which relates to prices stored in the database for an Offer. These prices are called through various relationships with other models, which is why I have not just tried something that may be able to group when running the query from the controller. Anyway, these prices have flags with the two I'm interested in being 'personal' and 'business'. At present querying the model would return data like this:
{
[
{'offer_id': 1, 'price': 345.30, 'personal': 1, 'business': 0},
{'offer_id': 1, 'price': 432.40, 'personal': 0, 'business': 1},
{'offer_id': 1, 'price': 464.50, 'personal': 1, 'business': 0},
{'offer_id': 1, 'price': 634.20, 'personal': 0, 'business': 1}
]
}
but what I would actually like to achieve is this:
{
"personal":
[
{'offer_id': 1, 'price': 345.30, 'personal': 1, 'business': 0},
{'offer_id': 1, 'price': 464.50, 'personal': 1, 'business': 0},
],
"business":
[
{'offer_id': 1, 'price': 432.40, 'personal': 0, 'business': 1},
{'offer_id': 1, 'price': 634.20, 'personal': 0, 'business': 1}
]
}
here is the model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class OfferPrice extends Model {
protected $fillable = ['offer_id', 'price', 'personal', 'business'];
public function offers()
{
return $this->belongsTo('App\Offer');
}
}
any help is greatly appreciated!
You can use the Collection method groupBy. By default any Eloquent query that returns more than one model will come in a collection.
$prices = OfferPrice::all()->groupBy(function ($offer) {
return $offer->personal === 1 ? 'personal' : 'business';
});
You can put this in a function like this
class OfferPrice extends Model {
...
public static function groupPersonalBusiness()
{
return self::all()->groupBy(function ($offer) {
return $offer->personal === 1 ? 'personal' : 'business';
});
}
}
Then use it like
$prices = OfferPrice::groupPersonalBusiness();
If you have an offer and define the inverse relationship you can use the groupBy there too since relationships also return a collection.
class Offer extends Model {
public function offerPrices()
{
return $this->hasMany('App\OfferPrice');
}
}
Then use it like
$prices = Offer::find(1)->offerPrices->groupBy(function ($offer) {
return $offer->personal === 1 ? 'personal' : 'business';
});