kohana 3.2 ORM find_all() with relationships

為{幸葍}努か 提交于 2019-12-10 12:12:58

问题


I have 3 tables:

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

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.

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();

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();

but it doesn't work for me.

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 />";
}

回答1:


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'),
        );

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;
    }
}

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



来源:https://stackoverflow.com/questions/8242630/kohana-3-2-orm-find-all-with-relationships

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