I have the database something like this
== Invoices ==
id
customer_id
== Customers ==
id
firstname
lastname
membersince
So I made relations in between both models like below.
Relation definition in the Invoices Model:
'customers'=>array(self::HAS_MANY,'Invoices','customer_id'),
Relation definition in the Customers Model
'invoices' => array(self::BELONGS_TO, 'Invoices', 'invoice_id'),
Now I want to know the relation in between both models are correct? Any suggestions are welcome.
No, the relation between the models is not correct.
I assume what you want here is that customers can have many invoices, but an invoice can only be owned by a single customer, as this is what your database schema implies.
Please note that in the code below I distinguish between singular and plural forms of customer and invoice to make the code logical and easy to understand.
In that case the relation definition in the
Invoicemodel would be like this:The invoice ‘belongs to’ a customer.
'Customer'indicates that the type of model we refer to is aCustomer, and'customer_id'is the name of the column in theinvoicestable that refers to the primary key of the customer.The
Customermodel looks a bit trickier:Here the relation definition indicates that a
Customercan refer to manyInvoicemodels. Notice how the rest of the relation is defined.customer_idis again the column that refers to aCustomer, and'index' => 'id'tells Yii to use the columnidin thecustomerstable as key for the relationship.You can find more information about the
relationsmethod in the Yii documentation.