Php Kohana(ORM)-如何从两个表中查找记录

Php Kohana(ORM)-如何从两个表中查找记录,php,kohana,kohana-3,kohana-orm,Php,Kohana,Kohana 3,Kohana Orm,这是我的桌子的外观,下面是我需要做的: class Model_Category extends ORM { protected $_has_many = array( 'film' => array('through' => 'films_categories') ); } class Model_Film extends ORM { protected $_has_many = array( 'c

这是我的桌子的外观,下面是我需要做的:

class Model_Category extends ORM
{     
    protected $_has_many = array(
        'film' => array('through' => 'films_categories')
    );
}

class Model_Film extends ORM
{        
    protected $_has_many = array(
        'categories' => array(
            'through' => 'films_categories'
        ),
}


films
-id (pk)
-title
-description

categories
-id (pk)
-name

films_categories
-film_id
-category_id

我需要找到包含$my_category='category table'的记录。有什么简单的方法可以做到这一点吗?

那么你想通过片名和类别来获得一部电影? 我将把ORM单独用于此查询,因为您将不会从中获得比查询生成器更大的好处:

$films->ORM::factory('film');
$films
    ->where('title', '=', $my_title)
    ->and_where('any of categories name', '=', $category_name)
    ->find_all();

我找到了答案。这有点不同,因为我想按电影的类别名称(或许多类别名称)查找电影。我发现按电影类别id查找电影更容易。如果有人觉得它很有用,请点击这里:

$films = DB::select()
    ->from('films')
    ->where('title', '=', $my_title)
    ->and_where($category_name, 'IN', DB::select()->from('categories')->execute()->as_array('id', 'name'))
    ->execute();

如果没有这一行,它会给出错误:

->select('*')

为什么join()在没有选择(“*”)的情况下不连接整个表?

如果仍要按类别名称筛选电影,则此操作应有效:

Kohana_Exception [ 0 ]: The category_id property does not exist in the Model_Film class
我想你需要

$films = ORM::factory('film')
    ->join('films_categories')->on('films_categories.film_id', '=', 'film.id')
    ->join(array('categories', 'category'))->on('category.id', '=', 'films_categories.category_id')
    ->where('film.title', '=', $film_title)
    ->where('category.name', '=', $category_name)
    ->find_all();
在查询中,因为您没有在where语句中指定列表。像这样:

->select('category_id')

它不起作用。$category_名称被视为列名,而不是变量。我需要得到与此类似的表:在join之后
$films = ORM::factory('film')
    ->join('films_categories')->on('films_categories.film_id', '=', 'film.id')
    ->join(array('categories', 'category'))->on('category.id', '=', 'films_categories.category_id')
    ->where('film.title', '=', $film_title)
    ->where('category.name', '=', $category_name)
    ->find_all();
->select('category_id')
->where('films_categories.category_id', '=', $category_id)