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

(11-07-2022, 06:00 PM)kenjis Wrote: Query Builder can use alias (short name).
https://codeigniter4.github.io/CodeIgnit...ilder.html

PHP Code:
$db      = \Config\Database::connect();
$builder $db->table('users u'); 

Thanks for the tip, but it doesn't appear to work for me. Is it because I am using a different style of query building? This is the only way I have ever done queries, so maybe what I originally learned was wrong?

This query:


PHP Code:
$this->newsModel = new \App\Models\NewsModel();
$records $this->newsModel 
    
->table('news n')
    ->select('n.id, n.title, n.created_at, n.is_active, u.firstname')
    ->join('users u','news.createdby_id = u.id','left')
    ->orderBy('is_active DESC, title ASC')
    ->findAll(); 


Produces an error:

PHP Code:
Unknown column 'n.id' in 'field list' 


While this query:


PHP Code:
$this->newsModel = new \App\Models\NewsModel();
$records $this->newsModel 
    
->from('news n')
    ->select('n.id, n.title, n.created_at, n.is_active, u.firstname')
    ->join('users u','news.createdby_id = u.id','left')
    ->orderBy('is_active DESC, title ASC')
    ->findAll(); 


Produces this (which is obviously wrong):


PHP Code:
SELECT `n`.`id`, `n`.`title`, `n`.`created_at`, `n`.`is_active`, `u`.`firstname`
FROM (`news`, `news` `n`)
LEFT JOIN `users` `uON `news`.`createdby_id` = `u`.`id`
ORDER BY `is_activeDESC, `titleASC 


In case it matters, here is the Model:


PHP Code:
namespace App\Models;

class 
NewsModel extends \CodeIgniter\Model
{
protected 
$table 'news';

protected 
$allowedFields = [
 
'title','article','url','is_active','createdby_id','updatedby_id','img_name'
 
];




This is a super simple query, figured that was best for testing/demonstration purposes. Where have I gone wrong? Am I using an old coding style or something?
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