Welcome Guest, Not a member yet? Register   Sign In
REST API one-to-many resource relationships
#1

how  can be  one to many relationships  in r rest full i4 
and mysql  database ?
Enlightenment  Is  Freedom
Reply
#2

(This post was last modified: 01-19-2021, 11:42 PM by bivanbi.)

I hope I understood your question correctly.

As far as I am concerned, CI does not inherently support one-to-many relation between relational database rows in its DB / entity logic. I myself solved this by creating a sort of higher-order database entity class that takes care of that.

As a side note, I do not expect CI to support it directly, as, in my opinion, it is beyond the scope of this lightweight framework.
Reply
#3

(01-19-2021, 11:41 PM)bivanbi Wrote: I hope I understood your question correctly.

As far as I am concerned, CI does not inherently support one-to-many relation between relational database rows in its DB / entity logic. I myself solved this by creating a sort of higher-order database entity class that takes care of that.

As a side note, I do not expect CI to support it directly, as, in my opinion, it is beyond the scope of this lightweight framework
okay i find he way tp manege problem i wanna show me your code too 
and i also share my code here too
Enlightenment  Is  Freedom
Reply
#4

Have you seen this addin?

https://github.com/tattersoftware/codeig...-relations
Reply
#5

(This post was last modified: 01-23-2021, 12:55 PM by paliz.)

(01-23-2021, 08:55 AM)nicojmb Wrote: Have you seen this addin?

https://github.com/tattersoftware/codeig...-relations
no  i ve never seen these

here s my code 

  before paste code here  i need expline  i have two data base which they connected by F-key  advertisement and advertisement_media 

code for migration  both tables
PHP Code:
<?php namespace App\Database\Migrations;

use 
CodeIgniter\Database\Migration;

class 
Advertisement extends Migration
{
//
    public function up()
    {

        /*
        * Setting
        */
        $this->forge->addField([
            'id' => ['type' => 'int''constraint' => 11'unsigned' => true'auto_increment' => true],
            'name' => ['type' => 'varchar''constraint' => 255],
            'link' =>  ['type' => 'varchar''constraint' => 255],
            'status' => ['type' => 'tinyint''constraint' => 1'null' => 0'default' => 1],
            'created_at' => ['type' => 'datetime''null' => true],
            'updated_at' => ['type' => 'datetime''null' => true],
            'deleted_at' => ['type' => 'datetime''null' => true],

        ]);

        $this->forge->addKey('id'true);
        $this->forge->createTable('advertisement'true);

    }

//--------------------------------------------------------------------

    public function down()
    {
        // drop constraints first to prevent errors
        if ($this->db->DBDriver != 'SQLite3') {
            // $this->forge->dropForeignKey('auth_tokens', 'auth_tokens_user_id_foreign');
        }

        $this->forge->dropTable('advertisement'true);
    }
}


////////////////////////////////////////////////////////////////////////

<?php namespace App\Database\Migrations;

use 
CodeIgniter\Database\Migration;

class 
AdvertisementMedia extends Migration
{

    public function up()
    {
        //

        /*
        * Setting
        */
        $this->forge->addField([
            'id' => ['type' => 'int''constraint' => 11'unsigned' => true'auto_increment' => true],
            'advertisement_id' => ['type' => 'int''constraint' => 11'unsigned' => true],
            'path' => ['type' => 'varchar''constraint' => 255],

        ]);

        $this->forge->addKey('id'true);
        $this->forge->addForeignKey('advertisement_id''advertisement''id'false'CASCADE');
        $this->forge->createTable('advertisement_media'true);

    }

    //--------------------------------------------------------------------

    public function down()
    {
        // drop constraints first to prevent errors
        if ($this->db->DBDriver != 'SQLite3') {
            // $this->forge->dropForeignKey('auth_tokens', 'auth_tokens_user_id_foreign');
        }

        $this->forge->dropTable('advertisement_media'true);
    }









code for  models  both tables




PHP Code:
<?php namespace App\Models;

use 
App\Entities\AdvertisementEntity;
use 
App\Entities\NewsPostEntity;
use 
CodeIgniter\Model;

class 
AdvertisementModal  extends Model
{
    protected $table 'advertisement';
    protected $primaryKey 'id';
    protected $returnType AdvertisementEntity::class;
    protected $allowedFields = [

        'name',
        'link',
        'status',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $useSoftDeletes false;
    protected $useTimestamps true;
    protected $createdField 'created_at';
    protected $updatedField 'updated_at';
    protected $validationRules = [
        'name' => 'required|min_length[3]|max_length[255]',
        'link' => 'required|alpha_numeric_punct',

    ];
    protected $validationMessages = [];
    protected $skipValidation false;



}



/////////////////////////////////
<?php namespace App\Models;

use 
App\Entities\AdvertisementMediaEntity;
use 
App\Entities\ContactFileEntity;
use 
App\Entities\NewsMediaEntity;
use 
CodeIgniter\Model;

class 
AdvertisementMediaModel extends Model
{
    protected $table 'advertisement_media';
    protected $primaryKey 'id';

    protected $returnType AdvertisementMediaEntity::class;
    protected $allowedFields = [
        'image',
        'advertisement_id',
        'path',


    ];


    protected $validationRules = [

    ];
    protected $validationMessages = [];
    protected $skipValidation false;







code for  entities  both tables




PHP Code:
<?php namespace App\Entities;

use \
CodeIgniter\Entity;
use 
CodeIgniter\I18n\Time;

class  AdvertisementEntity extends Entity
{

    public function __construct(array $data null)
    {
        parent::__construct($data);

    }

    protected $id;
    protected $name;
    protected $link;
    protected $status;
    protected $created_at;
    protected $updated_at;
    protected $deleted_at;


    protected $attributes = [
        'id' => null,
        'name' => null,
        'link' => null,
        'status' => null,
        'created_at' => null,
        'updated_at' => null,
        'deleted_at' => null,
    ];
    protected $datamap = [
    ];

    protected $dates = ['created_at''updated_at''deleted_at'];

    protected $casts = [
        'status' => 'boolean',
    ];

    protected $permissions = [];

    protected $roles = [];

    public function disableStatus()
    {
        $this->attributes['status'] = 0;
        return $this;

    }

    public function enableStatus()
    {
        $this->attributes['status'] = 1;

        return $this;
    }

    public function isStatus(): bool
    
{
        return isset($this->attributes['status']) && $this->attributes['status'] == true;
    }

    public function createdAt()
    {

      //  date_default_timezone_set('Asia/Tehran');
        $this->attributes['created_at'] = date('Y-m-d H:i:s'time());
        // $this->attributes['created_at'] = new  Time(date('Y-m-d H:i:s', time()), 'UTC');
        return $this;
    }

    public function updatedAt()
    {

      //  date_default_timezone_set('Asia/Tehran');
        $this->attributes['updated_at'] = date('Y-m-d H:i:s'time());

        return $this;
    }

}


/////////////////////////////////
<?php namespace App\Entities;

use \
CodeIgniter\Entity;
use 
CodeIgniter\I18n\Time;

class  AdvertisementMediaEntity extends Entity
{

    protected $id;
    protected $advertisement_id;
    protected $path;


    protected $attributes = [
        'id' => null,
        'advertisement_id' => null,
        'path' => null,

    ];
    protected $datamap = [
    ];

    protected $dates = [];

    protected $casts = [

    ];

    protected $permissions = [];

    protected $roles = [];


    public function editPath()
    {


        $this->attributes['path'] = 'public/upload/advertisement/' $this->attributes['path'];

        return $this;
    }




code for  resource controllers  both tables


PHP Code:
<?php

namespace App\Controllers\Api;


use 
App\Entities\AdvertisementEntity;
use 
App\Entities\NewsPostEntity;
use 
App\Libraries\ParameterDataInput;
use 
App\Models\AdvertisementMediaModel;
use 
App\Models\AdvertisementModal;
use 
CodeIgniter\HTTP\ResponseInterface;
use \
App\Models\NewsPostModal;

class 
Advertisement extends ApiController
{


    /**
     * index function
     * @method : GET
     */
    public function index()
    {
        $advertisementModel = new AdvertisementModal();

        $parameterDataInput = new ParameterDataInput();

        $parameterDataInput->receiveParameters();

        $result $advertisementModel->like($parameterDataInput->getFilterExplode('key'), $parameterDataInput->getFilterExplode('value'))->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))->paginate(10'default'$parameterDataInput->getPage());
        $advertisementMediaModel = new AdvertisementMediaModel();

        for ($i 0$i count($result); $i++)

            $result[$i]->media $advertisementMediaModel->where(['advertisement_id' => $result[$i]->id])->findAll();


        return $this->respond([
            'data' => $result,
            //'data' => $advertisementModel->like($parameterDataInput->getFilterExplode('key'), $parameterDataInput->getFilterExplode('value'))->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))->paginate(10, 'default', $parameterDataInput->getPage()),
            'pager' => $advertisementModel->pager->getDetails()
        ], ResponseInterface::HTTP_OK'get all  advertisement post');

    }

    /**
     * show function
     * @method : GET with params ID
     */
    public function show($id null)
    {

        $advertisementModel = new AdvertisementModal();
        $advertisementMediaModel = new AdvertisementMediaModel();

        $json $this->request->getJSON();
        if (!isset($id)) {
            $id $json->id;
        }

        $result $advertisementModel->where('id'$id)->paginate(1'default');
        for ($i 0$i count($result); $i++)
            $result[$i]->media $advertisementMediaModel->where(['advertisement_id' => $result[$i]->id])->findAll();

        return $this->respond([

            'data' => $result,
            'pager' => $advertisementModel->pager->getDetails()
        ], ResponseInterface::HTTP_OK'get  advertisement information');


    }

    /**
     * create function
     * @method : POST
     */
    public function create()
    {
        $advertisementModel = new AdvertisementModal();
        $advertisementEntity = new AdvertisementEntity();

        if ($this->request->getJSON()) {


            $rules = [
                'name' => 'required|min_length[3]|max_length[255]',
                'link' => 'required|alpha_numeric_punct',


            ];

            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_ACCEPTABLE'error during advertisement validate ');

            };

            $advertisementEntity->name $this->request->getJSON()->name;
            $advertisementEntity->link $this->request->getJSON()->link;
            $advertisementEntity->enableStatus();
            $advertisementEntity->createdAt();

            if (!$advertisementModel->save($advertisementEntity)) {

                return $this->respond([
                    'error' => $advertisementModel->errors(),
                    'success' => false,
                ], ResponseInterface::HTTP_BAD_REQUEST' cant save   advertisement  ');

            }

            return $this->respond([
                'insertId' => $advertisementModel->getInsertID()
            ], ResponseInterface::HTTP_CREATED' advertisement save successfully ');
        }

    }

    /**
     * update function
     * @method : PUT or PATCH
     */
    public function update($id null)
    {

        $advertisementModel = new AdvertisementModal();
        $advertisementEntity = new AdvertisementEntity();

        if ($this->request->getJSON()) {
            //get request from Vue Js
            $json $this->request->getJSON();
            if (!isset($id)) {
                $id $json->id;
            }


            $rules = [
                'name' => 'required|min_length[3]|max_length[255]',
                'link' => 'required|alpha_numeric_punct',


            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_ACCEPTABLE'error during edit  advertisement validate ');

            }

            $ads $advertisementModel->where('id'$id)->first();


            if (is_null($ads)) {


                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_FOUND'  advertisement  did not exist ');

            }


            $advertisementEntity->name $this->request->getJSON()->name;
            $advertisementEntity->link $this->request->getJSON()->link;
            $advertisementEntity->id $id;
            $advertisementEntity->status $this->request->getJSON()->status;
            $advertisementEntity->updatedAt();

            if (!$advertisementModel->update($id$advertisementEntity)) {

                return $this->respond([
                    'error' => $advertisementModel->errors(),
                    'success' => false,
                ], ResponseInterface::HTTP_BAD_REQUEST'error advertisement   ');

            }

            return $this->respond([
            ], ResponseInterface::HTTP_OK' advertisement information updated ');
        }


    }

    /**
     * edit function
     * @method : DELETE with params ID
     */
    public function delete($id null)
    {


        $advertisementModel = new AdvertisementModal();


        $json $this->request->getJSON();
        if (!isset($id)) {
            $id $json->id;
        }

        $isExist $advertisementModel->find($id);
        if ($isExist) {
            $advertisementModel->delete($id);

        }

        return $this->respond([
        ], ResponseInterface::HTTP_OK' advertisement delete it');


    }

}



////////////////////////////

<?php

namespace App\Controllers\Api;


use 
App\Entities\AdvertisementMediaEntity;
use 
App\Entities\NewsMediaEntity;
use 
App\Entities\ViewsMediaEntity;
use 
App\Libraries\HandyFunction;
use 
App\Libraries\ParameterDataInput;
use 
App\Models\AdvertisementMediaModel;
use 
App\Models\AdvertisementModal;
use 
CodeIgniter\HTTP\ResponseInterface;
use \
App\Models\NewsMediaModel;

class 
AdvertisementMedia extends ApiController
{


    /**
     * index function
     * @method : GET
     */
    public function index()
    {

        $advertisementMediaModel = new AdvertisementMediaModel();

        $parameterDataInput = new ParameterDataInput();

        $parameterDataInput->receiveParameters();


        return $this->respond([
            'data' => $advertisementMediaModel->like($parameterDataInput->getFilterExplode('key'), $parameterDataInput->getFilterExplode('value'))->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))->paginate(10'default'$parameterDataInput->getPage()),
            'pager' => $advertisementMediaModel->pager->getDetails()
        ], ResponseInterface::HTTP_OK'get all  advertisement media file');


    }

    /**
     * show function
     * @method : GET with params ID
     */
    public function show($id null)
    {
        $advertisementMediaModel = new AdvertisementMediaModel();

        $json $this->request->getJSON();
        if (!isset($id)) {
            $id $json->id;
        }


        return $this->respond([

            'data' => $advertisementMediaModel->where('id'$id)->paginate(1'default'),
            'pager' => $advertisementMediaModel->pager->getDetails()
        ], ResponseInterface::HTTP_OK'get advertisement media information');


    }

    /**
     * create function
     * @method : POST
     */
    public function create()

    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $customConfig = new \Config\Custom();
        $imageService = \Config\Services::image();
        $advertisementMediaEntity = new AdvertisementMediaEntity();


        if ($this->request->getPost()) {

            $rules = [
                'image' => 'uploaded[image]|max_size[image,4096]|ext_in[image,png,jpg,mp4,gif]'
            ];
            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false,
                    'fff'=>$this->request->getFiles()
                ], ResponseInterface::HTTP_NOT_ACCEPTABLE'error during advertisement media validate ');

            }


            if (isset($_FILES['image'])) {

                foreach ($this->request->getFileMultiple('image') as $avatar) {


                    $avatar->move($customConfig->uploadDirectory '/advertisement'time() . '.' $avatar->getClientExtension());

                    $advertisementMediaEntity->advertisement_id $this->request->getPost('advertisement_id');

                    $advertisementMediaEntity->path $avatar->getName();
                    $advertisementMediaEntity->editPath();

                    if (!$advertisementMediaModel->save($advertisementMediaEntity)) {

                        return $this->respond([
                            'error' => $advertisementMediaModel->errors(),
                            'success' => false,
                        ], ResponseInterface::HTTP_BAD_REQUEST'error advertisement media   ');

                    }
                }


            }


            return $this->respond([
                'data' => ''
            ], ResponseInterface::HTTP_CREATED'advertisement media save successfully ');

        }

    }

    /**
     * update function
     * @method : PUT or PATCH
     */
    public function update($id null){



        $advertisementMediaModel = new AdvertisementMediaModel();
        $customConfig = new \Config\Custom();
        $imageService = \Config\Services::image();
        $handy = new HandyFunction();
        $advertisementMediaEntity = new AdvertisementMediaEntity();

        if ($this->request) {

            $rules = [
                'image' => 'uploaded[image]|max_size[image,4096]|ext_in[image,png,jpg,,mp4,gif]'
            ];

            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false,
                    'fff'=>$this->request->getFiles()
                ], ResponseInterface::HTTP_NOT_ACCEPTABLE'error during advertisement media validate ');

            }


            $adsMedia $advertisementMediaModel->where('id'$id)->first();

            if (is_null($adsMedia)) {
                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_FOUND' advertisement media  did not exist ');

            }

            $isExist $advertisementMediaModel->where(['advertisement_id' => $this->request->getPost('advertisement_id')])->findAll();
            if ($isExist) {
                $advertisementMediaModel->where('advertisement_id'$this->request->getPost('advertisement_id'))->delete();
                foreach ($isExist as $path) {
                    $handy->removeSingleFile(ROOTPATH $path->path);
                }
            }

            if (isset($_FILES['image'])) {

                foreach ($this->request->getFileMultiple('image') as $avatar) {


                    $avatar->move($customConfig->uploadDirectory '/advertisement'time() . '.' $avatar->getClientExtension());

                    $advertisementMediaEntity->advertisement_id $this->request->getPost('advertisement_id');

                    $advertisementMediaEntity->path $avatar->getName();
                    $advertisementMediaEntity->editPath();

                    if (!$advertisementMediaModel->save($advertisementMediaEntity)) {

                        return $this->respond([
                            'error' => $advertisementMediaModel->errors(),
                            'success' => false,
                        ], ResponseInterface::HTTP_BAD_REQUEST'error advertisement media   ');

                    }
                }


            }


            return $this->respond([
            ], ResponseInterface::HTTP_OK' advertisement media information updated ');
        }

    }

    /**
     * edit function
     * @method : DELETE with params ID
     */
    public function delete($id null)
    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $handy = new HandyFunction();


        $json $this->request->getJSON();

        if (!isset($id)) {
            $id $json->id;

        }

        $isExist $advertisementMediaModel->where(['id' => $id])->findAll();
        if ($isExist) {
            $advertisementMediaModel->where('id'$id)->delete();
            foreach ($isExist as $path) {

                $handy->removeSingleFile(ROOTPATH $path->path);
            }

            return $this->respond([
            ], ResponseInterface::HTTP_OK'advertisement media delete it');

        }


    }


Enlightenment  Is  Freedom
Reply
#6

(This post was last modified: 01-23-2021, 02:20 PM by paliz.)

(01-23-2021, 08:55 AM)nicojmb Wrote: Have you seen this addin?

https://github.com/tattersoftware/codeig...-relations
thats oky for database rdbms but not  suitable for url  

url should be like these bellow 

[color=rgba(232, 230, 227, 0.9)]Use forward slash (/) to indicate hierarchical relationships[/color]


http://api.example.com/device-management
http://api.example.com/device-management...ed-devices
http://api.example.com/device-management...evices/{id}
http://api.example.com/device-management...d}/scripts
http://api.example.com/device-management...cripts/{id}





PHP Code:
$routes->get('x/new''X::new');
$routes->post('x/create''X::create');
$routes->post('x''X::create');  // alias
$routes->get('x''X::index');
$routes->get('x/show/(:segment)''X::show/$1');
$routes->get('x/(:segment)''X::show/$1');  // alias
$routes->get('x/edit/(:segment)''X::edit/$1');
$routes->post('x/update/(:segment)''X::update/$1');
$routes->get('x/remove/(:segment)''X::remove/$1');
$routes->post('x/delete/(:segment)''X::update/$1');

$routes->get('x/(:segment)/y/new''Y::new/$1');
$routes->post('x/(:segment)/y''Y::create/$1');
$routes->get('x/(:segment)/y''Y::index/$1');
$routes->get('x/(:segment)/y/(:segment)''Y::show/$1/$1');
$routes->get('x/(:segment)/y/(:segment)/edit''Y::edit/$1/$1');
$routes->put('x/(:segment)/y/(:segment)''Y::update/$1/$1');
$routes->patch('x/(:segment)/y/(:segment)''Y::update/$1/$1');
$routes->delete('x/(:segment)/y/(:segment)''Y::delete/$1/$1'); 


i personly decide not follow sub resource source and  url   


(01-23-2021, 08:55 AM)nicojmb Wrote: Have you seen this addin?

https://github.com/tattersoftware/codeig...-relations
i tested it  and i found  is equlavent to my solution too now it 's up to which  approaches  i choose
Enlightenment  Is  Freedom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB