문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top