doutuo8800 2017-01-04 05:53
浏览 27
已采纳

计算laravel中关系的关系

Suppose I have a Conversation model like this :

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');
    }

}

And a Question model like this:

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

As you can see there is a hasMany relation between those two.

In the other hand there is a Category like below that has a relation with Conversation model :

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

Now I want to append an attribute named question_count to Category that counts all questions of conversations of each category. for that I added this :

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

But when fetch a category I got this error :

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

What did I do? how can I count relations of a relation with minimum server overloading?

I am using laravel 5.3.4.

  • 写回答

3条回答 默认 最新

  • douzhaishan5462 2017-01-04 06:26
    关注

    I think that you need a has many through relationship here.

    What you do wrong:

    When you write $this->conversations->questions, this can't work, because the questions are a relation of a single conversation and not of a collection of conversations (here, $this->conversations is a Collection)

    The solution:

    Using hasManyThrough relation:

    You can find the documentation for this relation on this page, if my explanation is bad

    The basics are, you need to define a relation on your Category model:

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

    (I will let your look into the documentation for your non standards foreign keys)

    You should then be able to use: $category->questions->count()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析