0

I have a User table and a table for the cities, which I want to associate with each other. As you guess, a City can have multiple Users but one User can only be linked to one city.

I really don't know how to set my tables up. When I try $hasMany relation for the City and $hasOne for my User then I am getting an error, because the client_id field cannot be found in my cities table. My cities table is going to be fixed: no one will ever change the table. I just want to store some information about a city in this table.

Edit: Here are my tables and my models (kept simple):

clients { id, firstname, lastname, city_id }
cities { id, name, some_other_data }

And here are my models:

// User
class Client extends AppModel {
    public $hasOne = array(
        'City'
    );
}

// City
class City extends AppModel {
    public $useTable = 'cities';

    public $hasMany = array(
        'Client'
    );
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
lenny.myr
  • 903
  • 2
  • 11
  • 20
  • Could you update your question with the models (User and City if you have it), and you table's columns/names ? – Nunser Apr 19 '13 at 22:27
  • You have `User` and `City` table, but there supposed to be `users` and `cities`... Or rather `clients` and `cities` according to what I'm seeing in you models – Nunser Apr 19 '13 at 22:36
  • Thats not the matter. I followed CakePHP's naming conventions. My User Model can access the data. But I cant get the '$hasOne city' thing work, because when I set it I get this error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'City.client_id' in 'on clause' – lenny.myr Apr 19 '13 at 22:45

2 Answers2

2

You need to reverse the relation; A Client 'belongsTo' a city. (I know, this sounds illogical);

// User
class Client extends AppModel {
    public $belongsTo = array(
        'City'
    );
}

// City
class City extends AppModel {
    public $useTable = 'cities';

    public $hasMany = array(
        'Client'
    );
}

Your clients-table should contain a city_id field to make this work properly (just looked at your table-definition and it's already there, so just changing the Client-model should make it work for you).

thaJeztah
  • 27,738
  • 9
  • 73
  • 92
1

may be it will not work we have to specify foreignkey

    // User
class Client extends AppModel {
    public $belongsTo = array(
        'City'=> array(
        'className' => 'City',
        'foreignKey' => 'city_id'
     ) ,
    );
}
// City
class City extends AppModel {
    public $useTable = 'cities';

public $hasMany = array(
    'Client' => array(
        'className' => 'Client',
        'foreignKey' => 'city_id'
     ) ,
  ); 
}
liyakat
  • 11,825
  • 2
  • 40
  • 46
  • This should not be the problem, the OP has properly used the CakePHP conventions, so adding ClassName and foreignKey is *not* nescessary – thaJeztah Apr 20 '13 at 22:18