tattersoftware / codeigniter4-relations

Entity relationships for CodeIgniter 4
MIT License
87 stars 20 forks source link

Feature: Entity methods #1

Closed MGatner closed 4 years ago

MGatner commented 4 years ago

Should include a base entity with some relationship-smart methods, like:

Or maybe extended magic functions that check for relations?

MGatner commented 4 years ago

Some examples:

    // Check if this job has the requested file
    public function hasFile($fileId)
    {
        // Check if files are already loaded
        if (isset($this->attributes['files']))
        {
            foreach ($this->attributes['files'] as $file)
            {
                if ($file->id == $fileId)
                {
                    return true;
                }
            }

            return false;
        }

        // Check the database
        $builder = db_connect()->table('files_jobs');

        return (bool)$builder
            ->where('file_id', $fileId)
            ->where('job_id', $this->attributes['id'])
            ->countAllResults();
    }

    // Set files for a job in the database
    public function updateFiles($fileIds)
    {
        $builder = db_connect()->table('files_jobs');

        // Clear existing files
        $builder->where('job_id', $this->attributes['id'])->delete();
        unset($this->attributes['files']);

        // If there are no IDs then finish
        if (empty($fileIds))
        {
            return;
        }

        // Add back any selected files
        $rows = [];
        foreach ($fileIds as $fileId)
        {
            $rows[] = [
                'file_id' => $fileId,
                'job_id'  => $this->attributes['id'],
            ];
        }

        $builder->insertBatch($rows);
    }
MGatner commented 4 years ago

Added in version 2