【问题标题】:Kohana ORM - has many through models stored in parent modelKohana ORM - 有许多通过模型存储在父模型中
【发布时间】:2013-09-04 18:33:32
【问题描述】:

我在 has_many-through 关系方面遇到了很多问题,但最后我找到了很好的例子here,它解决了我的大部分问题。但是,根据下面提供的代码,我有几个问题。
首先,代码:

$artists = ORM::factory('artist')->find_all();
foreach ( $artists as $artist )
{
    foreach ( $artist->media->find_all() as $m )
    {
        echo $m->name;
    }
}

1) 这个例子可能是控制器。如果我想将media 存储在$artists 中以发送一个变量来查看怎么办?是否可以将media 作为媒体属性存储在艺术家对象中? (我的意思是例如$artists[0]->media[0]->name
2)没有这个循环是否可以完全加载$artists

【问题讨论】:

  • 为什么不在你的艺术家对象中创建一个名为media($key = NULL) 的函数并让它返回一个数组或单个对象?这将是简单的$artists[0]->media(0)->name,而$key 被排除在整个数组之外,这样也可以轻松集成缓存。

标签: php orm kohana


【解决方案1】:

1) 如果我理解正确,您需要从媒体中获取一些元素

$artists = ORM::factory('artist')->find_all()->as_array();
$media = $artists[0]->media->find_all()->as_array(); // media of first artist
$name = $media[0]->name;

2) 见上文 $artists 是一个 ORM 对象数组

【讨论】:

  • 不,我想把所有的变量都放在一个变量$artists 中(包括每个艺术家的媒体)。不过还是谢谢你的回答:)
【解决方案2】:

根据我的评论,这就是我要做的。

class Model_Artist extends ORM {

    ///
    /// Whatever you have now
    ///

    private $_media_cache = NULL;

    public function media($key = NULL)
    {
        // Check cache
        if($this->_media_cache == NULL)
        {
            $this->_media_cache = $this->media->find_all();
        }

        if($key !== NULL)
        {
             // Use Arr::get in case index does not exist
             // Return empty media object when it does not exist so you can 
             // 'harmlessly' ask for its properties
             return Arr::get($this->_media_cache, $key, ORM::factory('Media'));
        }

        return $this->_media_cache;
    }
}

可调用为

$artists[0]->media(0)->name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多