kohana 3.2 ORM find_all()与关系 [英] kohana 3.2 ORM find_all() with relationships

查看:66
本文介绍了kohana 3.2 ORM find_all()与关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3张桌子:

artists{id,name}
media{id,name,filename}
media_artists{artist_id,media_id}

我按照Kohana指南中的描述创建了具有n-n关系的模型.

I created the models with n-n relationships as described in the Kohana guide.

当我在控制器中操作时:

When I do in a controller:

$artist_view = new View('artists/profile'); 
$artist_id = $this->request->param('id');
$artist_view->artists = $artist_model->where('id', '=', $artist_id)->find();
$artist_view->media = $artist_model->media->find_all();

工作正常,我可以在视图中调用与此特定艺术家相关的媒体条目.

it works fine, and I can call the media entries related to this specific artist in my view.

现在,我想执行一个查询,以相同的sql结果获取所有艺术家及其相关媒体,但是找不到语法. 这个:

Now I want to do a query where I get all the artists, with their related media, all in the same sql result, but I don't find the syntax. This:

$artist_view->artists = $artist_model->order_by('name' , 'ASC')->find_all();
$artist_view->media = $artist_model->media->find_all();

不起作用(不会引发错误,但$ artist_view-> media为空)

doesn't work (doesn't throw an error but $artist_view->media is empty)

我在某些论坛上看到这样的方法可能有用:

I've seen on some forums that something like this might work:

$artist_model->order_by('name' , 'ASC')->with('media')->find_all();

但这对我不起作用.

在我看来,最后,我希望能够执行以下操作:

In my view, at the end, I want to be able to do something like this:

foreach($artists as $a){
echo $a->name."<br />";
foreach($a->media as $m) echo $m->name."<br />";
echo "<br />";
}

推荐答案

如果两个模型中的关系均定义如下:

If you have the relationhsip in both models defined as follows:

// In artist model.
protected $_has_many = array(
        'media' => array('through' => 'media_artists'),
    );
// In media model.
protected $_has_many = array(
                'artists' => array('through' => 'media_artists'),
        );

它应该可以使用(EDIT!):

It should work using (EDIT!):

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

我在一个项目中遇到了同样的问题,该解决方案对我有效(Kohana 3.2.0).

I had the same problem in one of my projects and this solution works for me (Kohana 3.2.0).

这篇关于kohana 3.2 ORM find_all()与关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆