【问题标题】:accessing data linked by foreign key in site view of custom component在自定义组件的站点视图中访问由外键链接的数据
【发布时间】:2013-10-15 23:06:05
【问题描述】:

在我的自定义组件中,在站点视图中,我有一个国家列表(视图:国家)。单击一个国家,将显示另一个视图(视图:人员),显示居住在该国家/地区的所有人员。

现在,在个人视图中,我想显示国家的名称和国旗。

所以我想在...site/models/persons.php 中添加一个function getCountry()

public function getCountry() {
    $db = $this->getDBO(); 
    $id = $this->state->get("filter.country");
    $sql = "SELECT * FROM #__cnlp_persons_country WHERE id = $id";
    $db->setQuery($sql); 
    $country = $db->loadResult(); 
    // var_dump($country);
    return $country; 
}

然后,我添加到.../site/views/persons/view.html.php

class Cnlp_personsViewPersons extends JView
{
    protected $items;
    protected $state;
    protected $params;
    protected $country; // <--- I added this
    ...

    public function display($tpl = null)
{
        $app                = JFactory::getApplication();
        $this->state        = $this->get('State');
        $this->items        = $this->get('Items');
        $this->params               = $app->getParams('com_cnlp_trainers');
        $this->country              = $this->get('Country'); // <--- I added this
        (...)

结果:我以为我可以在---/site/views/persons/tmpl/default.php 中使用类似...

<h1><?php echo $this->country->name; ?></h1>
<img src="<?php echo $this->country->flag; ?>" />

...但我得到没有输出... 我做错了什么?

【问题讨论】:

    标签: joomla joomla2.5 joomla-component


    【解决方案1】:

    $db-&gt;loadResult(); 用于加载单值结果(例如,如果您只想选择国家/地区名称或类似名称),但在您的查询中您选择的是整行,因此您应该使用一个这些人:

    $db->loadRow(); // returns an indexed array from a single record in the table
    $db->loadAssoc(); // returns an associated array from a single record in the table
    $db->loadObject(); // returns a PHP object from a single record in the table:
    

    您可以阅读有关此here 的更多信息(它是 joomla 1.5 文档,但它与 2.5 和 3 相同)

    【讨论】:

    • @michi 他们都做同样的事情,唯一的区别是他们如何返回结果:作为对象,作为数组或 assoc 数组。
    猜你喜欢
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2016-09-29
    • 2012-05-13
    • 2011-08-17
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多