We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Get specific children records

Hi,

Let's say I have the following two models:

class Country extends Model {
    public $id;
    public $name;

    public function initialize() {
        $this->hasMany("id", "City", "country_id", [
            'alias' => 'Cities'
        ]);
    }
}
class City extends Model {
    public $id;
    public $country_id;
    public $name;
    public $isCapital;

    public function initialize() {
        $this->belongsTo("country_id", "Country", "id", [
            'alias' => 'Country'
        ]);
    }
}

And an Iceland object:

$Iceland = Country::findFirstByName('iceland');

Is there a way to get the capital of Iceland from the $Iceland object ?

I know of the filter() method, which involves a user defined function, but I'd like to know if there's a more "compact" way. Something like:

// I know it's invalid
$IcelandCapital = $Iceland->Cities::findFirst(['isCapital' => 1]);

Thanks in advance.



98.9k
Accepted
answer

The following should work:

echo $Iceland->getCities('isCapital = 1')->name;


8.2k
edited Nov '14

OK, looks like it should be:

echo $Iceland->getCities('isCapital = 1')[0]->name;

but I get the idea. Thanks Phalcon, this is what I was looking for!