CodeIgniter Forums
ActiveRecord join with where clause - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: ActiveRecord join with where clause (/showthread.php?tid=43253)



ActiveRecord join with where clause - El Forum - 07-05-2011

[eluser]cyberjunkie[/eluser]
I'm having some trouble with active record. I have 2 database tables. One named users that retrieves general user data such as name, email, etc and table user_links that retrieves links that the respective user submitted.

I'm trying to return both general info and links in 1 page. I'm using the following code

Model:

Code:
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_links', "user_links.user_id = users.user_id"); //get links for respective user
$this->db->where('users.user_id', $user_id);
$this->db->where('user_links.user_id', $user_id);
$query = $this->db->get();
return $query->row();

Controller:

Code:
$this->load->model('User_model');
$data['row'] = $this->User_model->user_read($user_id); //$user_id is third URL segment
$this->load->view('profile/user_view', $data);

View:

Code:
<?php echo $row->first_name; ?>
<?php echo $row->last_name; ?>
etc...

With the where() function in the model I get

Code:
Trying to get property of non-object

Without it works but it's returning the first row in the database. I need the where clause. Can someone please tell me what I'm doing wrong?


ActiveRecord join with where clause - El Forum - 07-05-2011

[eluser]bubbafoley[/eluser]
are you sure the error is caused by the where() function? If select, from, join and get work then where should work too.

You aren't checking the query result before returning $query->row() in the model so $row in your view might not be an object.


ActiveRecord join with where clause - El Forum - 07-05-2011

[eluser]CodeIgniteMe[/eluser]
can you post the full error message?


ActiveRecord join with where clause - El Forum - 07-06-2011

[eluser]cyberjunkie[/eluser]
@bubbafoley, I'm not sure how to check query result before returning. It doesn't seem to work when the "user_links" table is empty for a specific user. You were right, the where() function is not the culprit.

I get

Code:
Severity: Notice

Message: Trying to get property of non-object

on codes such as

Code:
echo $row->first_name;

Is there a way to fix this issue?


ActiveRecord join with where clause - El Forum - 07-06-2011

[eluser]CodeIgniteMe[/eluser]
You must check first if there are results before you output them
Code:
if($query->num_rows()>0)
{
// blah blah blah
}