Models relation with Table::count();

Hey,

I use something like this which works fine.

$data = Server::count(['group' => 'modpack_id']);
foreach ($data as $key => $value) {
    echo "There are ", $value->rowcount, " in ", $value->modpack_id;
}

But now I want the modpack name from the foreign key table. I set the hasMany and belongsTo like always and it works fine with a normal select querie. But in this case I have no idea on how to manage it. Calling one extra query per modpack wouldn't be a good choice.

If something like this would work it would be great, is there a way to get it working, or how would you manage it?

$data = Server::count(['group' => 'modpack_id']);
foreach ($data as $key => $value) {
    echo "There are ", $value->rowcount, " in ", $value->modpack->name;
}


19.6k

If you had setted hasMany and belongsTo methods correctly, I think your code has to work without problems.



3.2k
edited Oct '14

I have and it works fine with a normal ::find query.

class Modpack extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->hasMany('id', 'server', 'modpack_id');
    }

class Server extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->belongsTo('modpack_id', 'modpack', 'id');
        $this->skipAttributesOnCreate(['disabled', 'creation_time', 'update_time', 'cache_time']);
    }


19.6k

If it works, I haven't catched correctly your question. You just wanna show the modpack name?



3.2k

Yeah, I have one table with the servers and each server has a modpack and it is linked via modpack_id. If I use Server::find() I can get the modpack name in volt with server.modpack.name or in php $server->modpack->name but this doesn't work if you use Server::count which i need in order to get the count of all servers for each modpack group without executing one query for each modpack.



19.6k
edited Oct '14

And what about doing an array, in wich you store each number of servers in each group? Later, in each iteration, you do a $array[modpackname]++

$array = array("modpack1name" => 2,
    "modpack2name" => 5
    ...
);