Loading Models with INNER JOIN

限于喜欢 提交于 2019-12-07 08:42:26

问题


Let's say I have a Phalcon\Mvc\Model that I load using ::findFirst($id).

How can I swap in a custom query that would load the model row and do INNER JOIN on some other table?

Thanks!


回答1:


I'm sure you can use the Query builder for simple joins like:

<?php

//Getting a whole set
$robots = $this->modelsManager->createBuilder()
    ->from('Robots')
    ->join('RobotsParts')
    ->orderBy('Robots.name')
    ->getQuery()
    ->execute();

//Getting the first row
$robots = $this->modelsManager->createBuilder()
    ->from('Robots')
    ->join('RobotsParts')
    ->orderBy('Robots.name')
    ->getQuery()
    ->getSingleResult();

Or PHQL example from the documentation:

<?php

$phql = "SELECT Robots.*
    FROM Robots JOIN RobotsParts p
    ORDER BY Robots.name LIMIT 20";
$result = $manager->executeQuery($phql);

By default, an INNER JOIN is assumed. You can specify the type of JOIN in the query though.

Reference: http://docs.phalconphp.com/en/latest/reference/phql.html#creating-queries-using-the-query-builder

Then I'd overload model's findFirst() method to utilize the above code and assign result values to model's properties.




回答2:


You are able to do this, you need to use the query static method on a Model which extends the Phalcon MVC Model class.

    $followingUsers = Users::query()
        ->leftJoin('Common\WideZike\Models\UsersFollowers', 'Common\WideZike\Models\Users.id = Common\WideZike\Models\UsersFollowers.followingId')
        ->where('Common\WideZike\Models\UsersFollowers.followerId = :userId:', array('userId' => $user->getId()))
        ->orderBy('Common\WideZike\Models\UsersFollowers.addedDate DESC')
        ->execute();

Hope this helps!




回答3:


$activations = UserActivations::query()
    ->columns("UserActivations.id")
    ->leftJoin("Deals", "d.id = UserActivations.dealId", "d") 
    ->where("UserActivations.state = 1")
    ->execute();


来源:https://stackoverflow.com/questions/21715835/loading-models-with-inner-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!