简体   繁体   中英

Conditioning by PK of the table belonged to in PHP-Activerecord

I'm fairly new using PHP-Activerecord, and I am not sure if this is do-able.

Three models; Foo, Bar and User.

Foo 1-0 Bar (Foo always assigned to Bar, Bar can have 1 or 0 Foo).

Bar N-1 User (Bar always assigned to User, User can have many Bar).

class Foo extends Model
{
    static $belongs_to = array(
        array('bar',
            'class_name' => 'Bar')
    );
}

class Bar extends Model
{
    static $belongs_to = array(
        array('user', 
            'class_name' => 'User')
    );
}

class User extends Model
{
    static $has_many = array(
        array('bar',
            'class_name' => 'Bar')
    );
}

Works if I do:

$bars = Bar::find('all', array(
    'user_id' => $userId
);

But I want the Foo's, not the Bars. So I've tried ...

$foos = Foo::find('all', array(
    'bar.user_id' => $userId
);

But it does not work; column user_id is not found.

How can I apply this condition?

You are looking for the 'through' relation.

This should work to get the Foo's of User through bar:

class User extends Model
{
    static $has_many = array(
        array(
            'bar',
            'class_name' => 'Bar'
        ),
        array(
            'foo',
            'class_name' => 'Foo',
            'through' => 'Bar' 
        )
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM