计算laravel

时间:2017-01-04 05:53:24

标签: php laravel laravel-5 eloquent laravel-5.3

假设我有Conversation这样的模型:

class Conversation extends Model
{
    public function questions (){
        return $this->hasMany('App\Question','conversation_id','conversation_id');
    }
    public function category ()
    {
        return $this->belongsTo('App\Category', 'cat', 'cat_id');
    }

}

这样的Question模型:

class Question extends Model
{
    public function conversation ()
    {
        return $this->belongsTo('App\Conversation', 'conversation_id', 'conversation_id');
    }
}

正如您所看到的,这两者之间存在hasMany关系。

另一方面,下面有CategoryConversation模型有关系:

class Category extends Node
{
    public function conversations (){
        return $this->hasMany('App\Conversation','cat','cat_id');
    }
}

现在,我想将一个名为question_count的属性附加到Category,该属性会计算每个类别对话的所有问题。为此我添加了这个:

    public function getQuestionsCountAttribute ()
    {
        return $this->conversations->questions->count();
    }

但是当获取类别时我收到了这个错误:

ErrorException in Category.php line 59:
Undefined property: Illuminate\Database\Eloquent\Collection::$questions

我做了什么?如何计算关系与最小服务器重载的关系?

我正在使用laravel 5.3.4。

3 个答案:

答案 0 :(得分:3)

我认为你需要一个有很多关系的人。

你做错了什么:

当您撰写/usr/test/req.log.2017-01-03-02.1.gz时,这不起作用,因为$this->conversations->questions单个会话的关系,而不是会话集合的关系(此处为{ {1}}是一个集合)

解决方案:

使用hasManyThrough关系:

如果我的解释不好,您可以找到此关系on this page的文档

基础知识是,您需要在questions模型上定义关系:

$this->conversations

(我将让您查看非标准外键的文档)

您应该可以使用:Category

答案 1 :(得分:2)

$ this->对话包含对话集合。每个会话都有自己的问题属性,其中包含该对话的所有相关问题,但该集合本身没有包含所有相关问题的问题属性类别。

为了能够计算该类别中所有问题的计数,您需要定义一个 hasManyThrough 关系,将问题直接链接到该类别。

首先,将关系添加到类别模型:

class Category extends Model {
  public function questions() {
    return $this->hasManyThrough('App\Question', 'App\Conversation', 'category_id', 'conversation_id', 'id');
  }
}

一旦你拥有它,你就能够得到一个类别的所有问题的计数:

public function getQuestionsCountAttribute ()
{
    return $this->questions()->count(); // if you only need the counter
}

答案 2 :(得分:1)

您可以使用' withCount'来计算相关模型。方法。 https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models

相关问题