我正在创建一个基本的论坛,只是为了让我有一些有意义的事情做,同时学习拉拉维尔。所以,就像组织每个论坛一样,在主页上,我希望有一个类别及其子类别的列表,每个子类别中的帖子总数,同时也有一个链接到最新的帖子。
因此,关系是嵌套的hasMany:
Category -> has Subcategories -> has Threads -> has Posts.
在控制器方法中
$cat = Category::with('subcategory')->get();
return View::make('forum.index', compact('cat'));
这适用于基本类别和子类别的列表,但我不知道其余的部分。这肯定不管用
Category::with('subcategory')->with('threads')->with('posts')->get();
因为它们之间的关系是不确定的。看看Laravel,就会发现hasManyThrough关系。这是解决办法吗?
class Category extends Eloquent {
public function subcategory() {
return $this->hasMany('Subcategory');
}
public function posts() { // not sure about this cause it doesnt work
return $this->hasManyThrough('Post', 'Thread');
}
}
最重要的是,我如何获得每个子类别的帖子->count()?有可能把它分开吗?链子会变得复杂..。
编辑表列是
类别
id | title
子范畴
id | title | category_id
线程
id | title | subcategory_id | user_id
帖子
id | title | body | thread_id | user_id
编辑2只获取最新帖子的代码是什么?这不管用
$data = Category::with('subcategories.threads')->with(array('posts' => function($query)
{
$query->take(1);
}))->get();
发布于 2014-09-11 15:50:55
您只设置了一个可以工作的关系,即:
class Category extends Eloquent {
public function subcategory() {
return $this->hasMany('Subcategory');
}
}
在其他模型中声明其他关系:
class Subcategory extends Eloquent {
public function threads() {
return $this->hasMany('Thread');
}
}
class Thread extends Eloquent {
public function posts() {
return $this->hasMany('Post');
}
}
一旦您声明了关系,那么您可以使用:
$categories = Category::with('subcategory.threads.posts')->get();
由于一个Category
有许多subcategories
,所以在Category
模型中使用subcategories
的复数名称而不是subcategory
,因此可以使用:
class Category extends Eloquent {
public function subcategories() {
return $this->hasMany('Subcategory');
}
}
然后还:
$categories = Category::with('subcategories.threads.posts')->get();
所有关系都将作为嵌套对象集合检索。例如:
$categories->subcategories; // Will be a collection of Subcategory models
$categories->subcategories->threads // Will be a collection of Thread models
$categories->subcategories->threads->posts // Will be a collection of Post models
您可以使用以下内容声明Subcategory
和Post
之间的Post
关系:
class Subcategory extends Eloquent {
public function threads() {
return $this->hasMany('Thread');
}
public function posts() {
return $this->hasManyThrough('Post', 'Thread');
}
}
此外,您还可以通过Category
和Thread
通过Subcategory
建立关系。
发布于 2019-02-06 23:15:55
我有QuestionCategory,Questions['category_id']
和ItemsOfQuestion['question_id']
,这个代码为我的代码工作,我希望这对你有用
$categories=ExamCategory::with(['question' => function ($query) use($exam){$query->where('exam_id','=',$exam->id)->with('Items');}])->get();
https://stackoverflow.com/questions/25798517
复制相似问题