![]() |
CI4 where should I connect to DB? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12) +--- Thread: CI4 where should I connect to DB? (/showthread.php?tid=76383) |
CI4 where should I connect to DB? - imabot - 05-07-2020 I'm writing models that use query builder with joints and many other funny stuf. Since CI4, we need to manually connect to the DB : Code: $db = \Config\Database::connect() Where should I place this connection line of code :
RE: CI4 where should I connect to DB? - php_rocs - 05-07-2020 @imabot, This documentation may assist you... https://codeigniter.com/user_guide/models/model.html#using-codeigniter-s-model RE: CI4 where should I connect to DB? - InsiteFX - 05-08-2020 PHP Code: Class NewModel extends Model You can then access the database using $this->db any where in your model. RE: CI4 where should I connect to DB? - jreklund - 05-08-2020 $this->db are already initialized in Model, no need to connect again. Only if you don't want to extend the "helper" model created for you. https://codeigniter.com/user_guide/models/model.html#manual-model-creation You can also use all function from the query builder directly. You don't need to do: Code: $this->db->countAll(); You can do: Code: $this->countAll(); RE: CI4 where should I connect to DB? - imabot - 05-09-2020 (05-08-2020, 08:25 AM)jreklund Wrote: $this->db are already initialized in Model, no need to connect again. Only if you don't want to extend the "helper" model created for you. Perfect answer, thank you. What if I have several database, are they all initialized automatically? RE: CI4 where should I connect to DB? - jreklund - 05-10-2020 (05-09-2020, 10:49 PM)imabot Wrote: Perfect answer, thank you. What if I have several database, are they all initialized automatically? No, that you are required to handle on your own. RE: CI4 where should I connect to DB? - imabot - 05-10-2020 Oops, it does not work : Quote:You must set the database table to be used with your query. Here is my code: Code: $builder = $this->table('tablename'); It only works with manual initialization. What am i doing wrong? RE: CI4 where should I connect to DB? - InsiteFX - 05-10-2020 PHP Code: $db = \Config\Database::connect(); RE: CI4 where should I connect to DB? - jreklund - 05-10-2020 @imabot: If that's in the model? For the primary database? If so, you need to configure your model first: https://codeigniter.com/user_guide/models/model.html#configuring-your-model You don't need to use $this->table. You just do: Code: $this->orderBy('id', 'DESC'); RE: CI4 where should I connect to DB? - imabot - 05-11-2020 (05-10-2020, 08:47 AM)jreklund Wrote: @imabot: If that's in the model? For the primary database? If so, you need to configure your model first: OK, got it. Thank you. |