【问题标题】:Kohana (ORM) - how to find record from 2 tablesKohana (ORM) - 如何从 2 个表中查找记录
【发布时间】:2011-10-04 17:30:16
【问题描述】:
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

这是我的表格的外观,这是我需要做的:

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

我需要找到包含 $my_category='any of category from category table' 的记录。有什么简单的方法吗?

【问题讨论】:

    标签: php kohana kohana-3 kohana-orm


    【解决方案1】:

    所以你想通过标题和类别来获得一部电影? 我会单独为这个查询留下 ORM,因为你不会从查询生成器中受益更多:

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

    【讨论】:

    【解决方案2】:

    我找到了答案。有点不同,因为我想通过类别名称(或许多类别名称)来查找电影。我发现通过 category_id 更容易找到电影。如果有人会在这里发现它有帮助,那就是:

    $category_id = 13;
    
    $films = ORM::factory('film')
                ->select('category_id')
                ->join('films_categories')
                ->on('films_categories.film_id', '=', 'film.id')
                ->where('category_id', '=', $category_id)
                ->find_all();
    
    
    foreach($films as $f)
        echo $f->title . " " . $f->category_id . "<br/>";
    

    我不知道它究竟是如何工作的,但确实如此。我偶然发明了这个。 如果有人能告诉我为什么需要这条线:

    ->select('category_id')
    

    ->select('*')
    

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

    Kohana_Exception [ 0 ]: The category_id property does not exist in the Model_Film class
    

    为什么 join() 在没有 select('*') 的情况下不能连接整个表?

    【讨论】:

      【解决方案3】:

      如果您仍想按类别名称过滤电影,这应该可以:

      $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 语句中指定列表。像这样:

      ->where('films_categories.category_id', '=', $category_id)
      

      【讨论】:

        猜你喜欢
        • 2012-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-08
        • 2011-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多