Phalcon 发现与模型关系的条件

Phalcon find with conditions of models relation

我有这个型号代码:

class TvguideChannel extends Model{

    public function initialize() {
        $this->setSource('tvguide_channel');
        $this->setConnectionService('db');

        $this->hasMany('code', __NAMESPACE__.'\Tvguide', "ch_code", ['alias' => 'Tvguide']);
    }

    public function getSource() {
        return 'tvguide_channel';
    } 
}

和控制器:

    $data = TvguideChannel::find();
    $dateDetails = $data->getTvguide(['order' => '$_POST["time"] DESC']);

    $paginator = new PaginatorModel(
        array(
            "data" => $data,
            "limit" => $limit,
            "page" => $curPage
        )
    );

    $items = $paginator->getPaginate();

这是行不通的。我如何在控制器中使用 Tvguide 模型中的列? 感谢您的帮助。

您的控制器代码将 return 一个 TvguideChannel 实例。 要访问关系,您必须使用上面定义的别名。

$data->Tvguide

以上应包含此记录的所有 Tvguide。

这里有一个更详细的例子 hasMany():

$this->hasMany(
    'id', // The primary key in your main table
    'Models\ServicesVideos', // The Model you are joining
    'service_id', // Foreign key for main table
    [
        'alias' => 'videos', // Alias which you use later to access the relation
        // additional parameters like where, order, limit etc...
        'params' => [
            'order' => 'position ASC',
            'conditions' => 'type = :type:',
            'bind' => [
                'type' => get_class($this)
            ]
        ]
    ]
);

UPDATE:将参数传递给关系本身的示例。

型号代码:

class Orders extends BaseModel
{
    public function initialize()
    {
        $this->hasMany('id', 'Models\OrderDetails', 'order_id', [
            'alias' => 'details',
        ]);
    }
 }

控制器代码:

// We want only related records with price higher than 9.00
$order = \Models\Orders::findFirst(17);
$orderDetails = $order->getDetails([
    'conditions' => 'price > 9.00'
]);

更新 2

find()方法return是一个Resulset,也就是说不能直接使用$data->getTvguide。您必须遍历每条记录并访问其相关条目。

$data = TvguideChannel::find();
foreach ($data as $item) {
    // This will return related guides for each channel.
    $dateDetails = $item->getTvguide(...);
}

如果您需要查找相关模型的位置,则需要使用查询生成器。