Welcome Guest, Not a member yet? Register   Sign In
Select with alias in model in CI 4
#1

Hello, I have this strange problem with a query on my CI4 project. There is a page that is really slow, so I've decided to print the sql query to see what's wrong with that and I've noticed this:

Code:
SELECT `mov`.*
FROM (`Movements`, `Movements` as `mov`)
JOIN `Articles` as `art` ON `art`.`id` = `mov`.`articleId`
GROUP BY `mov`.`id`
ORDER BY `id` desc
LIMIT 20

The table name was repeated and this causes a huge slowing of the table.


The code I've used in my model is:

Code:
$this->select('mov.*');
$this->from('Movements as mov');
$this->join('Articles as art', 'art.id = mov.articleId');
$this->groupBy("mov.id");
$this->orderBy("id");
$this->limit(20);

If I don't use alias query works good, but it's a little bit annoying to repeat the entire table name every time in the query:

Code:
$this->select('Movements.*');
$this->join('Articles as art', 'art.id = Movements.articleId');
$this->groupBy("Movements.id");
$this->orderBy("id");
$this->limit(20);

What am I missing?
Thank you
Reply
#2

When you get an instance of the BaseBuilder class, the database table specified in the model is added to it.
This is how the BaseBuilder class is designed.
That is, before you start using QueryBuilder, already called
PHP Code:
->from($this->table); 
//There it is a little different, but the meaning is the same. 

There is nothing you can do about it.

But you can reset the "from" section before using QueryBuilder.
PHP Code:
->from([], true); 
Reply
#3

Ok I understand. So there is no way to use aliases in this case?
I think will be great to have a property in model for alias.
Something like:

protected $table = 'Movements';
protected $tableAlias = 'mov';
protected $primaryKey = 'id';
Reply
#4

PHP Code:
->from('table as alias'true


But does it make sense?
You will still be manually specifying the alias in QB methods.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB