Welcome Guest, Not a member yet? Register   Sign In
Model Confusion
#1

[eluser]mdavis1982[/eluser]
Hi all...

I've been using CodeIgniter for quite a while now, but have always used the ActiveRecord class from the Wiki.

However, I've recently started work on a new project and am a bit confused how to use models properly with database interaction.

For example, in my current project I have a table in my database called 'users'. It has the following fields:

- id
- first_name
- last_name
- e-mail
- password
- web_site
- telephone

When people register on the site, their account is created by an administrator who fills in a form that just has their first name, last name and e-mail address.

How would I go about writing a 'create' method in my User model class, or do I need to do it some other way? With the ActiveRecord class I can just do:

Code:
$this->load->model('user');
$theUser = $this->user->create(array('first_name' => $first_name, 'last_name' => $last_name, 'e-mail' => $email, 'password' => $password, 'web_site' => NULL, 'telephone' => NULL);

However, all the examples I've seen assume that the $_POST array contains values for all fields in the table.

If I then wanted to select a specific member from the database, I could use:

Code:
$this->load->model('user');
$theUser = $this->user->find_by_id(12);

This would return an object of the current user. If I then needed to update the user, I could do:

Code:
$this->load->model('user');
$theUser = $this->user->find_by_id(12);
$theUser->first_name = 'Joe';
$theUser->last_name = 'Blogs';
$theUser->update();

How would I write some equivalent code in my model using the ActiveRecord class?

Also, where is the correct place to put methods that return arrays of objects? For example, in the AciveRecord class I can do:

Code:
$this->load->model('user');
$users = $this->user->find_all_by_first_name('Joe'); // Returns all the records which have a first name as 'Joe'
foreach($users as $user)
{
    echo $user->first_name . ' ' . $user->last_name . '<br />';
}

Sorry for the long post, but I am really confused about this and want to get it right the first time, so that I don't have to rewrite all the code afterwards. Any help would be greatly appreciated!

Thanks guys,

Matt
#2

[eluser]nmweb[/eluser]
Search on the forums and the wiki for ORM, there are plenty of libraries available to help you out.
#3

[eluser]mdavis1982[/eluser]
Hi nmweb...

I'm aware of all the libraries that are there to help me, but I want to knkow how to do it all without a library. It's great using one, but sometimes you just have to know how you should do it if the libraries didn't exist!

Any help would be greatly appreciated!

Cheers...

Matt




Theme © iAndrew 2016 - Forum software by © MyBB