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.

Get foreign key's field from find()


I want to know if it's possible to get directly all field of a foreign key. e.g

If I use findFirst I can do that :

$robot = Robots::findFirst(array(
    "conditions" => "id IN :id:",
    "bind" => array("id" => 1)

$partsName = $robot->getRobotsParts()->name;

But if I use a find I have to do that :

$data = array()
$robots = Robots::findFirst()

foreach ($robots as $robot) {
    $data['id'] = $robot->id;
    $data['partsName'] = $robot->getRobotsParts()->name;

But there is something to do that :

$robots = Robots::find(array(
    "columns" => "id, parts_name" // But in my Robots model I have just the `id_parts`. parts_name is in the parts table

echo $robots->toArray();

It's possible to select directly the parts_name column ?

edited Apr '18

Short answer - no. To achieve this you need a join, which is not possible with ORM. Either use your second example or even better - use the QueryBuilder which is much better in terms of performance. Your query should look something like this:

public function getRobotsWithPartNames()
    return $this->modelsManager->createBuilder()

        ->from(['robot' => 'Robots']) // <- make sure to specify full namespace here

        ->leftJoin('Models\RobotsParts', 'part.foreign_key =', 'part') // <- make sure to specify full namespace here and fix your key names


edited Apr '18

I think you could use:

$criteria->join("Robots", " = RobotsParts.robots_id");

to manually set the criteria and pass it to model's find method.


Thank you guys, so it's not possible with ORM ! Of course it's possible with the QueryBuilder :)

QueryBuilder is still part of ORM, it still uses PHQL.

A new comment How to avoid.

QueryBuilder is still part of ORM, it still uses PHQL. HAHAHHA