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.
69 lines
1.3 KiB
PHP
69 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App;
|
|
|
|
use Auth;
|
|
use App\Helpers\DateHelper;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class Task extends Model
|
|
{
|
|
protected $dates = ['completed_at'];
|
|
|
|
/**
|
|
* Get the account record associated with the task.
|
|
*/
|
|
public function account()
|
|
{
|
|
return $this->belongsTo('App\Account');
|
|
}
|
|
|
|
public function scopeCompleted(Builder $query)
|
|
{
|
|
return $query->where('status', 'completed');
|
|
}
|
|
|
|
public function scopeInProgress(Builder $query)
|
|
{
|
|
return $query->where('status', 'inprogress');
|
|
}
|
|
|
|
public function getTitle()
|
|
{
|
|
if (is_null($this->title)) {
|
|
return null;
|
|
}
|
|
|
|
return $this->title;
|
|
}
|
|
|
|
public function getDescription()
|
|
{
|
|
if (is_null($this->description)) {
|
|
return null;
|
|
}
|
|
|
|
return $this->description;
|
|
}
|
|
|
|
public function getCreatedAt()
|
|
{
|
|
return $this->created_at;
|
|
}
|
|
|
|
/**
|
|
* Change the status of the task from in progress to complete, or the other
|
|
* way around.
|
|
*/
|
|
public function toggle()
|
|
{
|
|
if ($this->status == 'completed') {
|
|
$this->status = 'inprogress';
|
|
} else {
|
|
$this->status = 'completed';
|
|
}
|
|
$this->save();
|
|
}
|
|
}
|