Reputation: 28783
I have two tables: Users and Profiles. A user may have a profile and a profile must have a user!
The tables are:
Users: id username email password
Profiles: firstname lastname gender dob user_id
So as you can see the profiles table links back to the users via the user_id key
How do I view a profile based on the username of that user?
As it needs to pull information from both tables... so far I have:
public function view ( $username )
{
$profile = $this->Profile->find('first', array(
'conditions' => array('User.username' => $username)
));
if (empty($profile))
{
$this->cakeError('error404');
}
$this->set(compact('profile'));
}
and this is the route for it:
Router::connect('/people/:userName',array('controller'=>'profiles','action'=>'view'),
array(
'userName'=>'[A-Za-z0-9\._-]+',
'pass'=>array('userName')
)
);
Also here are the Models:
User:
class User extends AppModel
{
var $name = 'User';
}
I have not specified the user hasOne profile, as the user may not have a profile. e.g admin account
Profile:
class Profile extends AppModel
{
var $name = 'Profile';
var $belongsTo = 'User';
}
and here is my view:
<h1><?php echo $profile['Profile']['firstname']; ?> <?php echo $profile['Profile']['lastname']; ?></h1>
But need some steer to get it correct. According to the CakePHP 2.0 book I can do something like: $this->User-Profile->
but I don't fully understand it or how I could use it here???
For example would this be correct:
$profile = $this->Profile->User->find('first', array(
'conditions' => array('User.username' => $username)
));
Thanks
Upvotes: 0
Views: 816
Reputation: 3701
According to your routes, you are going to use a 'User' model from ProfilesController. For this to work, you should add after the class ProfilesController extends Controller
the following line :
public $uses = array('User','Profile');
Then you get directly the User model like this :
$this->User->...
I may be wrong, but I don't think you could possibly do $this->Profile->User
[EDIT :]
after discussing this, it appears the User Model should really have $hasOne='Profile';
Because it does not enforce a profile, but just get it from database if it ever exists.
Upvotes: 1