CI4 where should I connect to DB? |
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 :
PHP Code: Class NewModel extends Model You can then access the database using $this->db any where in your model. What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
$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/model...l-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(); (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?
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?
@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/model...your-model You don't need to use $this->table. You just do: Code: $this->orderBy('id', 'DESC'); (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. |
Welcome Guest, Not a member yet? Register Sign In |