db
db copied to clipboard
`Query::leftJoin` - a simpler way to quote join column?
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Query\Query;
/**
* @var ConnectionInterface $database
* @var string $tableName
* @var string $childrenTableName
*/
$quoter = $database->getQuoter();
$quotedJoinColumn = $quoter->quoteTableName($tableName) . '.' . $quoter->quoteColumnName('name');
$rawItems = (new Query($database))
->select($tableName . '.*')
->from($tableName)
->leftJoin($childrenTableName, [$childrenTableName . '.child' => new Expression($quotedJoinColumn)])
->all();
You can use so code for quote:
$quotedJoinColumn = $quoter->quoteColumnName($tableName . '.name');
quoteColumnName() supports column names with table.
And simpler way will be so:
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Query\Query;
/**
* @var ConnectionInterface $database
* @var string $tableName
* @var string $childrenTableName
*/
$quoter = $database->getQuoter();
$quotedJoinColumn = $quoter->quoteColumnName($tableName . '.name');
$rawItems = (new Query($database))
->select($tableName . '.*')
->from($tableName)
->leftJoin(
$childrenTableName,
[$childrenTableName . '.child' => new Expression($quotedJoinColumn) ]
)
->all();
This could be done by one of the following ways:
-
By default for
...Join()methods process condition of associative array as"column name" => "column name", e.g.['parent.id' => 'child.parent_id']quote key and value of the associative array as column names. UseExpressionor parameters if need to pass value (not "column name"), e.g.['parent.id' => 'child.parent_id', 'child.has_parent' => new Expression('1'), 'child.has_parent' => ':param'] -
Add one more condition type, e.g.
column:['column', 'parent.id' => 'child.parent_id']and quote key and value as column names. This condition can be used in other places (not only in...Join()), e.g.->where(['column', 'parent.id' => 'child.parent_id']) -
Add specific class of
ExpressionInstancee.g.ColumnName:['parent.id' => new ColumnName('child.parent_id')]and quote it as column name. It also can be used in other palces (where(),having(), etc)
Also there is way
->leftJoin('child', ['parent.id' => new Expression('{{child}}.[[parent_id]]')])
In current implementation to $on bind params and used result string. And this OK for me, $on is not so often be a column name.
3th way from @Tigrov looks fine solution for this case.