Jojo Siao

Icon

enjoying life

my workaround: Cakephp model associations not in primary keys

I was just asked by another filipino cakephp developer about how to make model associations but the associations are not in primary keys. I already had been into this situation before, but I didn’t pursue a work around because, I felt it was not following good convention with regards to cakephp.

Well anyway, his db structure is like this. He has employees table , and belongs to Departments Table. But he said that an employee record has a department code. Meaning, to relate employees to departments, you must use a code. not an id, or a primary key.

I was a bit challenged. but it was easy to make a solution.

In short, I did this:
{code type=php}
var $belongsTo = array(
“Departments”=>array(
“className”=>”Departments”,
“foreignKey”=>”",
“conditions”=>”Employees.Deparment_code=Department.code”
)
);
{/code}

it works, wow!

Category: blog post

Tagged:

5 Responses

  1. ajmacaro says:

    another way is to set the primary key of the associated table.

    ex:
    $this->Employee->Department->primaryKey = ‘code’;
    $this->Employee->findById($x);

    watch for the generated SQL query.
    to understand more of it.

  2. jojo siao says:

    @ajmacaro,

    I couldn’t make your code work on me.
    Did you test it on your code?

  3. eric says:

    Thanks for the help jobert! helped me a lot!!

  4. ajmacaro says:

    Yes, i use it alot in project.
    just watch for generated query.

    maybe
    $x = $this->Employee->primary = ‘department_code’;
    $this->Department->findById($x);

    anyway, the idea was there, have fun exploring it.

  5. ajmacaro says:

    please edit the code.

    $this->Employee->primary = ‘department_code’;
    $this->Department->findById($x);

Leave a Reply