database icon indicating copy to clipboard operation
database copied to clipboard

NTDB joining tables on different key as primary key

Open apincik opened this issue 10 years ago • 0 comments

Table 'e_country'

id (int)
e_country_code (varchar(2))
name (varchar(50))

Indexes: PK(id), UNIQUE(e_country_code)

Second table:

Table 'p_product'
id (int)
country (varchar(2))

Indexes: PK(id), INDEX(country)
FK: country -> e_country(e_country_code)

1:N relation For example calling:

$this->dbContext->table("p_product")->select("p_product.*, country.e_country_code AS c_title");

The result:

SELECT `p_product`.*, `country`.`e_country_code` AS `c_title`
FROM `p_product`
LEFT JOIN `e_country` `country` ON `p_product`.`country` = `country`.`id`

If calling ref() on activeRow, the result in where clause is

`id` IN ("string", "string", "...")

Now, it gets p_product foreign keys from schema and replaces primary_key with column name on referenced table. So finall result will be:

LEFT JOIN `e_country` `country` ON `p_product`.`country` = `country`.`e_country_code`
...
`e_country_code` IN ("string", "string", "...") //ActiveRow->ref()

apincik avatar Dec 30 '15 21:12 apincik