Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to select some fields in related model in relationships?

Hi everyone,

For simplicity, I have 2 models

Client(id, username, password, full_name)
Request(id, client_id, fee, transfer_method, created_at, updated_at)

Client hasMany Request

I could do something like this:

$client = Client::findFirst("id = 1");
$requests = $client->request;

But if I only want to select the (id, fee, transfer_method) fields of Request model? How can I do that?

Thank you very much!


$requests = $client->getRequest(['columns' => 'id, fee, transfer_method']);

// or

$requests = $client->getRelated('Request', ['columns' => 'id, fee, transfer_method']);

$requests = $client->getRequest(['columns' => 'id, fee, transfer_method']);

// or

$requests = $client->getRelated('Request', ['columns' => 'id, fee, transfer_method']);

Thank Oscar. This is exactly what I asked for. But one more question, if I get some columns like this (I mean use getRequest method), the parent model will not include the child model, right?

For example, if I use $request = $client->request and then json_encode($client), each client will automatically include all requests belong to that client

If I use $request = $client->getRequest(), and then json_encode($client), each client will not contain requests belong to it.

It's weird

How to use $requests = $client->request but still can select which columns I need? Thank you

With $model->getRelated($alias) or $model->{"get" . $alias}() properties are not set to the model, and when selecting specific columns no Model instance is given as result, you will get a Phalcon\Mvc\Model\Row object.

You can create a getRequest() method and set inside the request property:


class Client extends Model {

    public function getRequest(array $parameters = NULL) {
        return ($this->request = $this->getRelated('Request', $parameters));