analogueorm / analogue

Analogue ORM : Data Mapper ORM for Laravel/PHP
MIT License
634 stars 51 forks source link

Problem hydrating relations #262

Closed DinoTD closed 5 years ago

DinoTD commented 6 years ago

Problem getting relations: class Product extends Entity { public $id; public $category_id; public $name; }

class ProductMap extends EntityMap
{
    protected $table = 'product';
    protected $arrayName = null;
    protected $attributes = null;
    protected $properties = ['id', 'category_id', 'name'];
    public function category(Product $prod)
    {
        return $this->belongsTo($prod, Category::class, 'category_id', 'id');
    }
}

class Category extends Entity { public $id; public $name; }

class CategoryMap extends EntityMap
{
    protected $table = 'categories';
    protected $arrayName = null;
    protected $attributes = null;
    protected $properties = ['id', 'name'];

    public function prods(Category $cat)
    {
        return $this->hasMany($cat, Product::class);
    }
}
    // This gets all products with category_id=2
    // makes 1 query from products and 1 from categories but foreach($prods as $prod) var_dump($prods->category) // is NULL
$prods = mapper(Product::class)->where(['category_id' => 2])->with('category')->get();
    // This gets the category with id=2
   // makes 1 query from products, 1 query for categories but $c->products is NULL
$c = mapper(Category::class)->where(['id' => 2])->with('products')->first();

Am I doing something wrong?

RemiCollin commented 6 years ago

When using property mapping (not using $attributes array), relationship should be defined as a property on the entity, of the same name as the relationship method. Also you should add the relationship name in the entityMap's '$properties` array.

DinoTD commented 5 years ago

Hi, It works for me now, thanks.

adrorocker commented 5 years ago

Closing as this was answered.