【发布时间】:2014-12-17 21:35:33
【问题描述】:
嗯,我的数据库中有这张表:
CREATE TABLE categories(
id INT,
name VARCHAR,
id_parent INT,
CONSTRAINT fk_categories FOREIGN KEY(id_parent) REFERENCES categories(id)
);
在 Laravel 类别模型中,我有这个:
class Category extends Eloquent
{
protected $table = "categories";
public function parentCategory(){
return $this->belongsTo("Category","id_parent");
}
public function subCategories(){
return $this->hasMany("Category","id_parent");
}
}
我也有这个数据:
id name id_parent
1 category_1 NULL
2 category_2 NULL
3 category_3 1
4 category_4 1
5 category_5 2
当我调用控制器时:
count(Category::with("subCategories")->get()); The count returns 5.
当我调用控制器时:
count(Category::has("subCategories")->get()); The count returns 0.
这一切都很糟糕,因为我只想要 parent_id = NULL 的类别,这将返回计数 3。
如果我使用count(Category::where("id_parent","!=","NULL"),结果是 3(没关系),但我想通过使用 HAS 或 WITH 函数得到这个结果。
那么,如何在不使用“where”功能的情况下做到这一点?
对不起我的英语。
【问题讨论】:
-
你这里有多少个表格和模型?我看到
categories表、其他一些表(“类别”?)以及至少 2 个模型Category和PropertyCategory,您询问自我关系。我想我不明白你的结构和你想要实现的目标 -
哦!对不起,我已经改变了所有的错误。模型是类别,引用的表是类别。我这样写是因为 laravel 说你必须用复数形式调用你的表,而用单数形式调用他的模型。
-
你应该考虑使用github.com/etrepat/baum。
标签: laravel laravel-4 eloquent query-builder relationships