Welcome Guest, Not a member yet? Register   Sign In
Nested Model Relations for CodeIgniter 4
#1

(This post was last modified: 03-13-2025, 10:10 AM by michalsn.)

This library simplifies managing model relationships (e.g., parent-child or related entities) in CodeIgniter 4. It extends the base model functionality, making it easier to define and work with nested relations. It supports eager and lazy loading.

GitHub Repository: codeigniter-nested-model

Installation:
Code:
composer require michalsn/codeigniter-nested-model

Example Usage:
Initialize nad define relations.
PHP Code:
use Michalsn\CodeIgniterNestedModel\Relation;
use 
Michalsn\CodeIgniterNestedModel\Traits\HasRelations;

class 
PostModel extends Model
{
    use HasRelations;

    // ...

    protected function initialize()
    {
        $this->initRelations();
    }

    public function author(): Relation
    
{
        return $this->hasOne(UserModel::class);
    }

Use in action:
PHP Code:
use App\Models\PostModel;

$postModel model(PostModel::class);

// Retrieve a post with its author relation
$post $postModel->with('author')->find(1);

// Access the related author data
echo $post->author->name

The best part is that it uses the same models you normally create, so you can take full advantage of this fact.

Docs:
https://michalsn.github.io/codeigniter-nested-model/
Reply
#2

Hello,
Have tried it, but get a Call to undefined method App\Models\PraticienModel::initRelations  exception.
Can't find out why.
Eric
Reply
#3

You probably forgot to add the HasRelations trait to your model.
Reply
#4

(This post was last modified: 03-06-2025, 12:28 PM by foxbille.)

no...
    Have followed instructions scrupulously
    Started a fresh CI4 installation with composer create-project
    Then added codeigniter-nested-model
    checked everything i could (Model, Entity, controller, route)
    Then deleted folder and made it twice again
    Tried to add full path to HasRelation :
    use Michalsn\CodeIgniterNestedModel\Traits\HasRelation;
    Nothing could fix the problem
Reply
#5

The trait's name is plural - HasRelations (with an "s" at the end).
Reply
#6

I know, it's a typo in my post, script is fine.
Reply
#7

got it!
use \Michalsn\CodeIgniterNestedModel\Traits\HasRelations;
was outside model class definition Sad
now i get :
Method "specialite()" returned an incorrect type. ("App\Models\Relation" instead of "Michalsn\CodeIgniterNestedModel\Relation")
What am I doing wrong?
Reply
#8

You need to import the Relation class:
PHP Code:
use Michalsn\CodeIgniterNestedModel\Relation

I updated the docs - now examples have full imports of necessary classes, to prevent these types of confusion.

https://michalsn.github.io/codeigniter-n...sic_usage/
Reply




Theme © iAndrew 2016 - Forum software by © MyBB