Optimized (sub-)booking methods and index view for eager loading.

This commit is contained in:
Lukas Halbritter
2018-09-30 21:38:25 +02:00
parent 07ec0482a0
commit 3f6fe26ff0
4 changed files with 155 additions and 128 deletions
+74 -32
View File
@@ -6,50 +6,92 @@ use Illuminate\Database\Eloquent\Model;
class Booking extends Model
{
public function amount()
{
return $this->subBookings()->sum('amount');
}
public function signedAmount()
{
return $this->subBookings()->withSignedAmount()->get()
->sum('signedAmount');
}
/**************************************************************************
* DIRECT RELATIONS *
**************************************************************************/
/**
* Return all sub-bookings which belong to the booking.
*
* @return Illuminate\Database\Eloquent\Relations\HasMany
*/
public function subBookings()
{
return $this->hasMany('App\SubBooking');
}
/**************************************************************************
* INDIRECT RELATIONS *
**************************************************************************/
/**
* Get the project to which the booking belongs. If the booking consists of
* more than one sub-booking, null is returned.
*
* @return App\Project
*/
public function project()
{
if ($this->isSimple()) {
return $this->subBookings->first()->project;
}
return null;
}
/**
* Get the account type of the booking. If the booking consists of more than
* one sub-booking, null is returned.
*
* @return App\AccountType
*/
public function accountType()
{
if ($this->isSimple()) {
return $this->subBookings->first()->accountType;
}
return null;
}
/**************************************************************************
* INDIRECT PROPERTIES *
**************************************************************************/
/**
* Get the (unsigned) amount of all sub-bookings.
*
* @return float
*/
public function amount()
{
return $this->subBookings->sum('amount');
}
/**
* Return the sum of all signed amounts of all sub-bookings related to the
* booking.
*
* @return float
*/
public function signedAmount()
{
$sum = 0;
foreach ($this->subBookings as $subBooking) {
$sum += $subBooking->signedAmount();
}
return $sum;
}
/**
* Return true, if the booking consists only of one sub-booking.
* NOTICE: The book instance has to be loaded with the
* ->withCount('subBookings') method to be able to access the comments
* count.
*
* @return boolean
*/
public function isSimple()
{
return $this->sub_bookings_count === 1;
}
public function project()
{
if ($this->isSimple()) {
return $this->subBookings()->first()->project();
}
return null;
}
public function accountType()
{
if ($this->isSimple()) {
return $this->subBookings()->first()->accountType();
}
return null;
return $this->subBookings->count() === 1;
}
}