Ben
Ben

Reputation: 1368

How to read CakePHP Model using specific fields?

I'm new to CakePHP and I'm stuck in reading a Model using other fields. I did a cake bake command to generate a simple users CRUD. I can view the user using the url CakePHP provided.

/users/view/1

I can view the user using id = 1. What if I want to view a user by name instead of id?

/users/view/username

By default the view function reads the User model by id.

$this->User->read(null, $id)

Thank you.

Upvotes: 0

Views: 1518

Answers (3)

metrobalderas
metrobalderas

Reputation: 5240

It seems that CakePHP is focusing to deprecate some functions, such as findAll(). Perhaps soon the magic methods such as findBy<field>() will have the same fate.

I can recommend what martswite is suggesting, you should create your custom function:

function findUser($username=''){
    return $this->find('first', array(
        'conditions' => array(
            'User.username' => $username
        )
    ));
}

Perhaps you have a status field, maybe the profile isn't public, you can add a condition:

function findUser($username=''){
    return $this->find('first', array(
        'conditions' => array(
            'User.username' => $username,
            'User.status' => 1
        )
    ));
}

I think that's more modular than findBy<Field>.

Upvotes: 0

RSK
RSK

Reputation: 17516

you can use find function or findBy<Field>() in your case findByUsername()

check this

Upvotes: 1

martynthewolf
martynthewolf

Reputation: 1708

I've never used cakePHP myself but I'm going to suggest that you will likely have to implement a new user model method, something like getUserByUsername($username) This would then in turn interface with your DAL that would get the details of that user based on the username and return a user object that can be used however you wish...

Upvotes: 0

Related Questions