Reputation: 115
I have three tables:
Schema example:
Customer has a Customer Number
Item can have multiple Prices belonging to different Customers
One Price belongs to one Item and one Customer
Item-Model:
class Item extends AppModel {
public $hasOne = 'Price';
//...
}
Price-Model:
class Price extends AppModel {
public $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'id'
)
);
So what happens now is: One Item has 3 different Prices for 3 different Customers. I get all Items automatically (one item 3 times) but i want only the items for the currently logged in Customer (identified by customer_number, a field which appears in this tables:
Any suggestions? Thank you.
Upvotes: 2
Views: 2983
Reputation: 13952
First up, follow CakePHP conventions: your customers
table should have an id
column. And your prices
table should have a customer_id
column, which is the foreign key to your customers
table. If you need a human-friendly 'customer number', separate from the customer's id, used to identify that customer, then it can be an extra field in the customer's table, but it should not be duplicated across to the prices table.
Second, you've defined in your Item model that a Item hasOne Price. That's actually not true - an Item has many prices - one for each customer.
What you're after in this situation is a HasMany through relationship. Read that documentation - you'll end up with something like this:
// Customer.php
class Customer extends AppModel {
public $hasMany = array(
'Price'
);
}
// Item.php
class Item extends AppModel {
public $hasMany = array(
'Price'
);
}
// Price.php
class Price extends AppModel {
public $belongsTo = array(
'Customer', 'Item'
);
}
Your prices table will need a customer_id
column, and an item_id
column.
Next, when returning items for the currently logged in Customer, you could do a find on your Price model, joined to your Item model, where price.customer_id equals the id of the relevant customer.
Upvotes: 2