fuel / orm

Fuel PHP Framework - Fuel v1.x ORM
http://fuelphp.com/docs/packages/orm/intro.html
151 stars 95 forks source link

fix for empty has_many relation #442

Closed ysshir closed 3 years ago

ysshir commented 3 years ago

tables..

parent
id name
1 parent1
2 parent2
3 parent3
child
id parent_id name
1 1 child1
2 3 child2
grand_child
id child_id name
1 1 grand_child1
2 1 grand_child2
3 2 grand_child3
4 2 grand_child4

Models...

class Model_Parent extends Orm\Model {

    protected static $_table_name  = 'parent';
    protected static $_primary_key = ['id'];
    protected static $_properties  = [
        'id',
        'name',
    ];

    protected static $_has_many = [
        'children' => [
            'key_from' => 'id',
            'model_to' => 'Model_Child',
            'key_to'   => 'parent_id',
        ],
    ];
}
class Model_Child extends Orm\Model {

    protected static $_table_name  = 'child';
    protected static $_primary_key = ['id'];
    protected static $_properties  = [
        'id',
        'parent_id',
        'name',
    ];

    protected static $_belongs_to = [
        'parent' => [
            'key_from' => 'parent_id',
            'model_to' => 'Model_Parent',
            'key_to'   => 'id',
        ],
    ];

    protected static $_has_many = [
        'grand_children' => [
            'key_from' => 'id',
            'model_to' => 'Model_GrandChild',
            'key_to'   => 'child_id',
        ],
    ];
}
class Model_GrandChild extends Orm\Model {

    protected static $_table_name  = 'grand_child';
    protected static $_primary_key = ['id'];
    protected static $_properties  = [
        'id',
        'child_id',
        'name',
    ];

    protected static $_belongs_to = [
        'child' => [
            'key_from' => 'child_id',
            'model_to' => 'Model_Child',
            'key_to'   => 'id',
        ],
    ];
}

problems

try {
    $parent = \Model_Parent::query()
                           ->related(['children', 'children.grand_children'])
                           ->order_by('id')
                           ->get();
} catch(Exception $e) {
    // sad :(  
}
WanWizard commented 3 years ago

Looks like a great fix, thanks!