家庭任務平台中主要使用了使用者,計畫,任務,活動,個人資料這五者的關係分別為
家庭任務平台中的Model各為:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function projects()
{
return $this->hasMany('App\Project', 'owner_id');
}
public function tasks()
{
return $this->hasMany('App\Task', 'assignee_id');
}
public function profile()
{
return $this->hasOne('App\Profile');
}
public function getProjects()
{
return Project::where('owner_id', $this->id)
->orWherehas('members', function (Builder $query) {
$query->where('member_id', $this->id);
})->orderBy('updated_at', 'desc')->get();
}
public function activities()
{
return $this->hasMany('App\Activity');
}
public function invitedProject()
{
return $this->belongsToMany('App\Project', 'member_project', 'member_id', 'project_id');
}
}
class Project extends Model
{
use Recordability;
protected $fillable = ['note', 'title', 'description', 'owner_id'];
public function owner()
{
return $this->belongsTo('App\User', 'owner_id');
}
public function tasks()
{
return $this->hasMany('App\Task');
}
public function addTask(array $task)
{
$this->tasks()->create($task);
}
public function activities()
{
return $this->morphMany('App\Activity', 'recordable');
}
public function members()
{
return $this->belongsToMany('App\User','member_project','project_id','member_id');
}
public function invite(User $member)
{
MemberProject::firstOrCreate([
'member_id'=>$member->id,
'project_id'=>$this->id
]);
}
}
ps. 在app的資料夾中加入trait:Recordability
trait Recordability
{
public function recordActivity(string $description, $changes = [])
{
$user_id = $this->activityOwner();
$this->activities()->create(['user_id'=>$user_id,'description' => $description, 'changes' => $changes]);
}
protected function activityOwner()
{
if(Auth::check()){
return Auth::id();
}
if(class_basename($this) === 'Project'){
return $this->owner->id;
}elseif(class_basename($this) === 'Task'){
return $this->project->owner->id;
}
}
}
篇幅有點太長了,明天繼續:
Model(Task):對應資料表(tasks)
Model(Activity):對應資料表(activities)
Model(Profile):對應資料表(profiles)
Model(MemberProject):對應資料表(member_project)