Welcome Guest, Not a member yet? Register   Sign In
Not sure how to get a value from model and use in controller
#1

What I want to do is get a value from a model and use it in my controller to update another model.

The problem is I have a database of locations and parts, the parts are in a specific location based on locationID. But if the location name gets updated or deleted the old location name is still in the parts. So the way I thought I should do it is in my update method for the location in my controller is 

1. get the location name/location ID that the person wants to edit based on the URI segment for the location

2. put that location in a variable in the controller

3. update all location data (in the locations table) with input data from the user

4. update all part location data (in parts table) that matches the old location name that we put in that variable from step 2.



The main problem I have is how to get and use the locationID, locationName values from the model and use them in the controller. I've only used values from model to contoller to view before. Am I going about this right? If so how can I get the values and put them in variables to use in the controller? Thanks
Reply
#2

I would suggest that you only keep the location ID in the parts and lookup the location name when needed. Then you are not repeating data in your tables and will avoid these issues.

To get a variable from a model just return the value you need and use it. Or return an array and use the required key value.

Hope that helps,

Paul.
Reply
#3

that does make a lot more sense... That seems like a no brainer, I guess it slipped my mind. Thanks Paul haha
Reply
#4

I do have other needs for using values from the model in a controller though. Is there a good way to do something like above?
Reply
#5

Make a function in your model that returns a value (or an array of values).

Simplified example:
Model: (Parts_model.php)
PHP Code:
public function get_parts($location_id)
{
  $record $this->db->get_where('parts','location_id='.$location_id)->row_array();
  return $record;

Controller:
PHP Code:
$this->load->model('parts_model');
$needed_parts $this->parts_model->get_parts(44);
//$needed_parts is an array, containing the fields of one record 
Reply
#6

Thanks!
Reply
#7

(08-05-2015, 11:39 PM)Wouter60 Wrote: Make a function in your model that returns a value (or an array of values).

Simplified example:
Model: (Parts_model.php)
PHP Code:
public function get_parts($location_id)
{
  $record $this->db->get_where('parts','location_id='.$location_id)->row_array();
  return $record;


Why create a variable, which uses more memory, when you are just going to return its value?

PHP Code:
public function get_parts($location_id)
{
  
//just return the value, no variable needed.
  return $this->db
    
->get_where('parts','location_id='.$location_id)
    ->
row_array();

Reply




Theme © iAndrew 2016 - Forum software by © MyBB