Model association with custom table and key names

和自甴很熟 提交于 2019-12-10 19:35:01

问题


I'm using php.activerecord, and I am trying to link two tables.

I have contacts and contactCompanyLinks. Each contact can contain one or more rows in the link table. The field names in the table don't follow any sensible convention, but I can't change it as it would break another app using the same table.

The primary key of contacts is called contactID, and the foreign key in contactCompanyLinks is called inspectorID.

php.activerecord makes way too many assumptions, and I can't figure out how to get it to link my tables together.

Here are my models:

Contact.php:

<?php
class Contact extends ActiveRecord\Model {
    static $primary_key = 'contactID';

    static $has_many = array(
        array(
            'contactCompanyLinks',
            'class_name' => 'ContactCompanyLink',
            'foreign_key' => 'inspectorID'
        )
    );
}

ContactCompanyLink.php:

<?php
class ContactCompanyLink extends ActiveRecord\Model {
    static $table_name = 'contactCompanyLinks';

    static $belongs_to = array(
        array('contact')
    );
}

This looks right, but when I tried to get a row, it's not working. I did the following:

<?php
var_dump(Contact::find(1234)->contactcompanylinks);

All I got printed to the screen was NULL! If I tried other properties like contactcompanylink or ContactCompanyLink or ContactCompanyLinks, I got an "undefined property" error.

var_dump(Contact::find(1234) works just fine. It shows me the fields from the contacts table.

How do I tell php.activerecord to stop assuming things and listen to me when I try to tell it how to link 2 tables together?


回答1:


The undefined property-error comes probably from your ID. phpactiverecord assumes, nay FORCES all properties to be lowercase.

This means that all the fields should be called lowercase. E.G., your keys should be inspectorid and contactid.

Not that this is the case for columns only. Class names (php classes) should obviously be the case they actually are, and so should table names.

I always explicitly define ALL elements of a connection to avoid that assumption problem. This means both connection will have all elements for me:

static $belongs_to = array(
  array('somename',
        'foreign_key'=>'someid',
        'primary_key'=>'id', 
        'class_name'=>'Models\\NameSpace\\YourModelClassName')
);

but also the same fields are needed for the has_many. The primary in the belongs_to is the id of the OTHER table, and the foreign key is the key in this table (and when I say key, I mean the column name). For the belongs to the foreign key is the key in the other table, and the primary key the key in this table.

Also, mind the double slashes for the namespace.



来源:https://stackoverflow.com/questions/13868791/model-association-with-custom-table-and-key-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!