So that I understand what you are looking for correctly.
Table Products
id |
name |
1 |
Printer |
2 |
Software |
Table Types
id |
product_id |
type |
weight |
1 |
1 |
physical |
1.5 |
2 |
1 |
physical |
2.5 |
3 |
1 |
physical |
3.5 |
4 |
2 |
downloadable |
null |
5 |
2 |
downloadable |
null |
6 |
2 |
downloadable |
null |
Models
class Products
{
public initialize()
{
$this->setSource('products');
// All products
$this->hasMany(
'id,
Types::class,
'product_id',
[
'alias' => 'types',
'reusable' => true,
]
);
// Physical
$this->hasMany(
'id,
Types::class,
'product_id',
[
'alias' => 'physical',
'reusable' => true,
'params' => [
'conditions' => 'type = :type:',
'bind' => [
'type' => 'physical',
]
]
]
);
// Downloadable
$this->hasMany(
'id,
Types::class,
'product_id',
[
'alias' => 'downloadable',
'reusable' => true,
'params' => [
'conditions' => 'type = :type:',
'bind' => [
'type' => 'downloadable',
]
]
]
);
}
}
Queries:
Products::find()
// one query returns 2 records
$product->getRelated('products')
// one query - returns all records related to this product
$product->getRelated('physical')
// one query - returns all physical related to this product
$product->getRelated('downloadable')
// one query - returns all downloadable related to this product
That is if you use find
and getRelated
.
If you use the builder you can get all the data in one go:
$builder = new Builder();
$data = $builder
->columns('p.id, t.type, p.name, t.weight')
->addFrom(Products::class, 'p')
->innerJoin(Types::class, 'id = product_id', 't')
->orderBy('t.type, p.name')
->executeQuery()
....
That will be one query for both tables and all the data.
Can you explain a bit on what you really wanted to do? According to the issue you opened here the resultset you want back is a multi dimentional array/object that groups things according to what you want (in this case the product type)?