mondo
mondo

Reputation: 354

Cakephp One-way relationship

I have Items and Units, and want each Item to have one Unit, but that unit can be used by many.

Items Table

id - int

name - varchar

description - varchar

unit_id - int

Units Table

id - int

name - varchar

description - varchar

Items Model

var $hasOne = array( 'Units' => array( 'className' => 'Unit' ) );

Units Model Nothing, but previously I tried: var $belongsTo = array( 'Items' => array( 'className' => 'Item' ) );

When I'm in the scaffolding (List Items) I get:

Warning (512): SQL Error: 1054: Unknown column 'Units.item_id' in 'on clause' [CORE/cake/libs/model/datasources/dbo_source.php, line 684]

And in the Edit Item screen, the Units drop-down is empty. Any idea what I'm doing wrong? Essentially the Units table are just to populate a drop-down in the Item entry form, but I'd like it to auto-populate in scaffold.

Upvotes: 0

Views: 147

Answers (1)

deceze
deceze

Reputation: 521995

Your Item belongsTo a Unit and your Unit hasMany Items.

belongsTo - foreign key is in the current model (unit_id of Item)
hasMany - foreign key is in the related model
hasOne - foreign key is in the related model and there's only one
hasAndBelongsToMany - foreign keys are in a separate third table

Upvotes: 1

Related Questions