|
| 1 | +# CodeIgniter Nested Model |
| 2 | + |
| 3 | +Dead simple nested model relations for CodeIgniter 4 framework. |
| 4 | + |
| 5 | +### Example |
| 6 | + |
| 7 | +```php |
| 8 | +// app/Models/UserModel.php |
| 9 | +<?php |
| 10 | + |
| 11 | +namespace App\Models; |
| 12 | + |
| 13 | +use CodeIgniter\Model; |
| 14 | +use Michalsn\CodeIgniterNestedModel\NestedModelTrait; |
| 15 | + |
| 16 | +class UserModel extends Model |
| 17 | +{ |
| 18 | + use NestedModelTrait; |
| 19 | + |
| 20 | + ... |
| 21 | + |
| 22 | + protected $relations = [ |
| 23 | + // one avatar - relation type, model, foreign key, local key |
| 24 | + 'avatar' => ['hasOne', AvatarModel::class]//, 'user_id', 'id'], |
| 25 | + // many social links - relation type, model, foreign key, local key |
| 26 | + 'links' => ['hasMany', LinkModel::class]//, 'user_id', 'id'], |
| 27 | + ]; |
| 28 | +} |
| 29 | +``` |
| 30 | +```php |
| 31 | +// app/Config/Routes.php |
| 32 | +<?php |
| 33 | + |
| 34 | +... |
| 35 | + |
| 36 | +$routes->get('nested', static function () { |
| 37 | + |
| 38 | + // get all users with avatar and links |
| 39 | + d(model(UserModel::class)->with('avatar')->with('links')->findAll()); |
| 40 | + |
| 41 | + // get user with id = 2 and all links |
| 42 | + d(model(UserModel::class)->with('links')->find(2)); |
| 43 | + |
| 44 | + // get user with id = 2 and links with type 'test' |
| 45 | + d(model(UserModel::class)->with('links', static function () { |
| 46 | + return model(LinkModel::class)->where('type', 'test'); |
| 47 | + })->find(2)); |
| 48 | + |
| 49 | +}); |
| 50 | + |
| 51 | +... |
| 52 | +``` |
0 commit comments