Kohana (ORM) - 如何从 2 个表中查找记录
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='类别表中的任何类别'的记录。有什么简单的方法可以做到这一点吗?
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
This is how my tables looks and here is what I need to do:
$films->ORM::factory('film');
$films
->where('title', '=', $my_title)
->and_where('any of categories name', '=', $category_name)
->find_all();
I need to find record that has $my_category='any of categories from category table'. Any simple way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么您想通过标题和类别获取一部电影吗?
我将单独为该查询保留 ORM,因为您不会从它中获得比查询生成器更多的好处:
So you're trying to get a movie by its title and category?
I'd leave ORM for this query alone, since you won't benefit from it more then from query builder:
我找到了答案。没什么不同,因为我想通过类别名称(或许多类别名称)查找电影。我发现通过电影的category_id 更容易找到电影。如果有人觉得它有帮助的话,那就是:
我不知道它到底是如何工作的,但确实如此。我偶然发明了这个。
如果有人可以告诉我为什么需要这一行:
或者
没有这一行,它会给出错误:
为什么 join() 不会在没有 select('*') 的情况下连接整个表?
I found an answer. It's little different, because I wanted to find movie by its category name (or by many category names). I found easier to find movie by its category_id. If someone would find it helpfull here it is:
I dont know how it exactly works, but it is. I invented this by accident.
And if someone could tell me why this line is needed:
or
without this line it gives and error:
why join() doesn't join whole tables without select('*') ?
如果您仍然想按类别名称过滤电影,这应该可行:
而且我想您在查询中需要
,因为您没有在 where 语句中指定列表。像这样:
If you still want to filter out films by category name this should work:
And I guess you need
in your query, cause you don't specify column table in your where statement. Like this: