arif-rh / ci4-dynamic-model

动态创建带有内置关系功能的CodeIgniter 4模型。

0.3.7 2021-06-08 20:27 UTC

This package is auto-updated.

Last update: 2024-09-09 04:10:50 UTC


README

CodeIgniter 4 动态模型

Build Status Coverage Status

功能

  • 动态即时创建模型
  • 支持一对一/多对一关系
  • 支持一对多关系
  • 可以基于子/相关标准过滤数据
  • 可以基于子标准设置一对多关系结果的排序

安装

composer require arif-rh/ci4-dynamic-model

使用

简单

    // creating postModel on-the-fly, just pass a table name
    $postModel = \Arifrh\DynaModel\DB::table('posts');

    // then you can use it, to get all posts
    $postModel->findAll();

多对一关系

    // assume that posts always belongs to one author using author_id 
    $postModel->belongsTo('authors);

    // then you can grab author info along with posts
    $postModel->with('authors')->findAll();

    /**
    * by default, primary key of authors will be omit in the column result
    * because its value already exist in the foregin key of relationship
    * 
    * if authors has same column name with posts, then it will be aliased with prefix "author_"
    * for example, both posts and authors has "rating" column, then it will become author_rating
    */

    // you can call only spesific column if you need, pass it on the second parameters in array
    $postModel->with('authors', ['name', 'rating'])->findAll(); 
    // will display all posts column, plus author name and author rating

    // you can filter posts based on author criteria
    $postModel->with('authors')->whereRelation('authors', ['status' => 'active'])->findAll();
    // will display all posts only from active authors

一对多关系

    $postModel->hasMany('comments');

    // this will return posts with all related comments
    $postModel->with('comments')->findAll();

    // you can also filter posts based on comments criteria
    $postModel->with('comments')->whereRelation('comments', ['status' => 'approved'])->findAll();
    // will display all posts with approved comments only

测试

    composer test

    // or

    composer testdox

    // analyse code
    composer analyse