繁体   English   中英

Laravel关系

[英]Laravel relations

我正在创建一个基本论坛,以便在学习Laravel时可以做一些有意义的事情。 因此,就像组织每个论坛一样,在主页上,我希望有一个类别及其子类别的列表,每个子类别中的帖子总数,同时还链接到最新帖子

所以关系嵌套了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');
    }
}

除此之外,我如何为每个子类别获取posts-> 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();

您仅设置了一种有效的关系,即:

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 ,以便使用复数名称subcategories ,而不是subcategory中的Category模型,因此,例如,你可以使用:

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

您可以使用以下内容声明SubcategoryPost之间的hasManyThrough关系:

class Subcategory extends Eloquent {

    public function threads() {
        return $this->hasMany('Thread');
    }

    public function posts() {
        return $this->hasManyThrough('Post', 'Thread');
    }
}

另外,您可以通过SubcategoryCategoryThread之间建立关系。

我有QuestionCategory和Questions['category_id']ItemsOfQuestion['question_id']此代码对我有用,希望对您有用

$categories=ExamCategory::with(['question' => function ($query) use($exam){$query->where('exam_id','=',$exam->id)->with('Items');}])->get();

查看我的答案,可能会有所帮助

http://stackoverflow.com/questions/16210628/laravel-relationships

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM