Welcome Guest, Not a member yet? Register   Sign In
Controller and sql
#1

Hello,

Can I user   something like this
$db = \Config\Database::connect();    
 $query =  $db->query('select * from mytable');  or whatever query to process the result.
inside a Controller instead of model 
what will be the risk of using this kind sql stuff inside Controller ?
also what is the advantage of  Model ?

Thank you
Reply
#2

Yes, you technically can do that, but it's not recommended.

Controllers and Models are simply classes that are used to handle different things. Controllers should be responsible for controlling the flow from the request, getting the data together, and sending information back to the client.

A Model represents a single database table and has lots of built-in methods to make it easier to work with that table, including built-in functionality to handle the basic create, read, update, and delete methods as well as more advanced functionality.

The benefit of keeping them separate is a reuse of functionality. If you do the raw query in several controllers, and find that you need to change something, then you have to change it everywhere and not just in one place. There's 2 ways you could handle this using a model, the second option being the best long-term solution.

The "Raw Query" way:

PHP Code:
// In the controller
$users db_connect()
  ->
table('users')
  ->
where('role'$role)
  ->
get()
  ->
getResultArray(); 

First Option:

PHP Code:
// In the controller
$rows model('UserModel')
  ->
where('role'$role)
  ->
findAll(); 

This at least uses the model to pull the records (and is much more readable than the raw query method). It also makes it so that if you find you need to modify the records when you retrieve them and opt to use an afterFind event all places you grab that data will benefit without any extra work.

Second:

PHP Code:
// In the UserModel
public function getByRole(string $role)
{
  return 
$this
    
->where('role'$role)
    ->
findAll();
}

// In the controller
$users model(UserModel::class)->getByRole($role); 

This is the recommended solution for anything other than the simplest query. It isolates the actual query away from anyplace that needs the users. Where you need the users, you don't need to know how the users are pulled from the database to work. Now, if you change the way that roles are stored in the database (like pull it into a pivot table instead of hard-coded on the user table so that they can have more than one), you can handle that logic in one location in the model.
Reply
#3

It's not recommened because it breaks the MVC Pattern ( Model View Controller).
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

(This post was last modified: 01-27-2023, 02:10 PM by lindaw.)

Thank you for the clear explanation, I will redo my work to use model instead, thanks again
Reply




Theme © iAndrew 2016 - Forum software by © MyBB