Files
monica/app/SignificantOther.php
T
Yamamoto Kadir 50005544ee Fix some relationship inconsistencies and reduce dashboard queries (#209)
This normalizes all relationships and adds relations to models to take advantage of laravel's eagerloading and reduce queries to the database.

This might go against the 'add any kind of complexities whatsoever' rule in the contribution guide, but I think adding relations would eventually simplify the code base. The amount of queries just on the dashboard fell from ~70 to 26. There's also a lot of boilerplate code in the Contact model to retrieve relationships and to maintain accurate count of them (fields like number_of_*). They can be greatly simplified with the addition of relations.

One other thing in the Contact model was the definition of the Contact-User relation. This definition uses the account_id field in the contacts table and and relates it to id in users. I'm not sure if this is the intention, since the id from accounts table is used when assigning account_id for a contact. This seems to have worked so far, because both a user and its associated account are created at the same time during registration and their ids match, but if there was any difference, this relationship would relate wrong contacts and users. I changed the relationship name to account. This makes the path to a user from a contact is $contact->account->user right now.
2017-06-11 23:01:23 -04:00

98 lines
1.9 KiB
PHP

<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class SignificantOther extends Model
{
protected $table = 'significant_others';
protected $dates = [
'birthdate',
];
/**
* Get the account record associated with the significant other.
*/
public function account()
{
return $this->belongsTo('App\Account');
}
/**
* Get the contact record associated with the significant other.
*/
public function contact()
{
return $this->belongsTo('App\Contact');
}
/**
* Limit the query to active significant others
*
* @param Builder $query
* @return Builder
*/
public function scopeActive(Builder $query)
{
return $query->where('status', 'active');
}
/**
* Get the first name of the significant other.
*
* @return string
*/
public function getName()
{
if ($this->first_name == '') {
return null;
}
return $this->first_name;
}
/**
* Get the birthdate of the contact.
*
* @return Carbon
*/
public function getBirthdate()
{
if (is_null($this->birthdate)) {
return null;
}
return $this->birthdate;
}
/**
* Gets the age of the contact in years, or returns null if the birthdate
* is not set.
*
* @return int
*/
public function getAge()
{
if (is_null($this->birthdate)) {
return null;
}
$age = $this->birthdate->diffInYears(Carbon::now());
return $age;
}
/**
* Returns 'true' if the birthdate is an approximation
*
* @return string
*/
public function isBirthdateApproximate()
{
return $this->is_birthdate_approximate;
}
}