Welcome Guest, Not a member yet? Register   Sign In
Table short name and queries
#10

(11-09-2022, 12:30 AM)davis.lasis Wrote: As far as i can see (without testing my-self), you have a syntax error in your example code.
You have `n` not `news` and order_by must have those tables in-front of table columns as well
PHP Code:
$db      = \Config\Database::connect();
$builder $db->table('news n');
$builder->select('n.id, n.title, n.created_at, n.is_active, u.firstname')
    ->join('users u','n.createdby_id = u.id','left')
    ->orderBy('n.is_active DESC, n.title ASC');
$query $builder->get(); 

I often use many joins, the biggest i have i think was 9 joins
1. you can collect all your selects first
PHP Code:
$select 'table1.field1';
$select .= ', table2.field2, table2.field3, table2.field4';
$select .= ', table3.field8, table3.field9';

$db = \Config\Database::connect();
$builder $db->table('table1');
$builder->select($select)
 ->
join('table2''...''left')
 ->
join('table3''...''left'); 

2. you can use manually written query
PHP Code:
$sql 'SELECT field1 FROM table1 WHERE id = 10';
$results $this->db->query($sql)->getResultArray(); 


P.S. i never shorten database table names. Yes - it's longer writing, but:
- if you have error - easier to spot which table / column issue you have in query
- if i have like 5 joins, then tables like `n`, `u`, `m`, `i` - in the big picture does not make sense
- if you need to change table name - long table name can be find / replaced easily in all instances, because in 99% it will be unique, with shortening try to find / replace `n` in code !

Reading the comments above, I am beginning to think the way I am creating my queries is the wrong approach. Should I be using the $builder instead of the way I have since I started with CI? What are the drawbacks to my approach versus the $builder approach?
Reply


Messages In This Thread
Table short name and queries - by SoccerGuy3 - 11-07-2022, 04:37 PM
RE: Table short name and queries - by kenjis - 11-07-2022, 04:53 PM
RE: Table short name and queries - by SoccerGuy3 - 11-07-2022, 05:36 PM
RE: Table short name and queries - by kenjis - 11-07-2022, 06:00 PM
RE: Table short name and queries - by SoccerGuy3 - 11-08-2022, 09:49 AM
RE: Table short name and queries - by kenjis - 11-08-2022, 04:46 PM
RE: Table short name and queries - by SoccerGuy3 - 11-08-2022, 04:50 PM
RE: Table short name and queries - by davis.lasis - 11-09-2022, 12:30 AM
RE: Table short name and queries - by SoccerGuy3 - 11-09-2022, 05:25 PM
RE: Table short name and queries - by kenjis - 11-09-2022, 12:37 AM
RE: Table short name and queries - by SoccerGuy3 - 11-10-2022, 08:56 AM
RE: Table short name and queries - by kenjis - 11-10-2022, 06:42 PM
RE: Table short name and queries - by SoccerGuy3 - 11-11-2022, 07:18 AM



Theme © iAndrew 2016 - Forum software by © MyBB