如何在查询 Eloquent 中指定关系条件
How in query Eloquent specify condition with relations
我有 2 个表:
文章
编号 |标题 | category_id | created_at | updated_at |
和类别
编号 |姓名 |说明 | created_at | updated_at |
关系:类别 hasMany-> articles
和文章 belongsTo -> category
。
如何简单地进行查询:
public functions getArticles ($category) {
$articles = Articles::where('category', '=', $category);
}
文档中存在带有 Id (http://laravel.com/docs/4.2/eloquent#one-to-many ) 的示例,但我想要 select 篇文章,知道名称类别。
如何在查询中指定关系条件?
如果有这样的方法,请帮帮我。
谢谢 ;)
您可以使用whereHas
方法。喜欢:
$articles = Articles::whereHas('category', function($query)use($category){
$query->where('name', $category->name);
});
我想这应该行得通。或者你可以创建一个 scope
并加入 categories
table 然后检查它。
我有 2 个表:
文章
编号 |标题 | category_id | created_at | updated_at |
和类别
编号 |姓名 |说明 | created_at | updated_at |
关系:类别 hasMany-> articles
和文章 belongsTo -> category
。
如何简单地进行查询:
public functions getArticles ($category) {
$articles = Articles::where('category', '=', $category);
}
文档中存在带有 Id (http://laravel.com/docs/4.2/eloquent#one-to-many ) 的示例,但我想要 select 篇文章,知道名称类别。
如何在查询中指定关系条件?
如果有这样的方法,请帮帮我。 谢谢 ;)
您可以使用whereHas
方法。喜欢:
$articles = Articles::whereHas('category', function($query)use($category){
$query->where('name', $category->name);
});
我想这应该行得通。或者你可以创建一个 scope
并加入 categories
table 然后检查它。