Raoul
(Manu34)
April 27, 2015, 6:28pm
1
Hi,
when using yii\db\Query it is required in some cirumstances to include the table name (for instance to disambiguate column names).
… but the table name may not be constant if for example it includes a prefix.
Question : What is the best way to handle such case ?
Should I write something like that ? :
$customers = Customer::find()
->select('customer.*')
->leftJoin('order', '`'.$this->tableName().'`.`customer_id` = `customer`.`id`')
->where([$this->tableName().'.status' => Order::STATUS_ACTIVE])
->with('orders')
->all();
assuming $this refers to an ActiveRecord instance
Or is there a better way ?
ciao
$this refers to context where you are. It could be in model or in Controller, according where you are write this code.
manoelt
(Reefbr)
April 27, 2015, 6:49pm
3
To include the prefix, use {{%table_name}}.
Raoul
(Manu34)
April 27, 2015, 7:09pm
4
Thanks to both of you… but I do know how to setup table prefix in the Model, and how to get it
My question was : is there a better way than calling tableName() to refer to the table name in a query where I must include it ?
I suspect there is not but maybe I’m wrong.
ciao
madand
(Dev Madand)
April 27, 2015, 9:17pm
5
Hi Raoul,
you are right that tableName() is the only "right" way to get the table name of the AR class.
However, since ActiveRecord::tableName() is a static method, I would recommend to call it
in static context with explicit AR class:
$customers = Customer::find()
->select(Customer::tableName() . '.*')
->leftJoin(Order::tableName(), '`'.Customer::tableName().'`.`customer_id` = `customer`.`id`')
->where([Customer::tableName().'.status' => Order::STATUS_ACTIVE])
->with('orders')
->all();
// more DRY way
$customerTable = Customer::tableName();
$customers = Customer::find()
->select("$customerTable.*")
->leftJoin(Order::tableName(), '`'.$customerTable.'`.`customer_id` = `customer`.`id`')
->where([$customerTable.'.status' => Order::STATUS_ACTIVE])
->with('orders')
->all();
By explicitly specifying the AR class names, you can easily re-use parts of your queries, in various contexts, where $this might be something different.
Raoul
(Manu34)
April 28, 2015, 7:20pm
6
Thanks for this valuable advice that I will follow.