dongxun5349
2018-01-16 16:33
浏览 14
已采纳

如何获得Laravel的Belongsto伯爵?

I want to get the count of the elements of materials count.

SubCategory:

public function materials(){
        return $this->hasMany('App\Material');
    }

Materials:

 public function subcategories(){
        $this->belongsTo('App\SubCategory','SubCategoria_id');
    }

I want to get the count of the elements that have the subcategory_id

'quantidade' => $subcategory->material->count()

I'm getting error in 1054 Unknown column 'material.subcategory_id'

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doubai9014 2018-01-16 16:36
    已采纳

    Since you're using a custom foreign key, you need to specify it. So, change the relation to:

    public function materials()
    {
        return $this->hasMany('App\Material', 'SubCategoria_id');
    }
    

    And then use the proper relationship name:

    $subcategory->materials()->count()
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duannengling4705 2018-01-16 16:35

    Does your material table have a subcategory_id column? This error could indicate it doesn't exist, therefore it's failing when you try the relationship.

    As long as the column exists, the relationship should be valid and you should be able to count the results.

    评论
    解决 无用
    打赏 举报
  • douqiang1851 2018-01-16 16:35

    You should use the relationship to count. This will count the items using the DB. You should use the function like this:

    'quantidade' => $subcategory->materials()->count()
    

    And in the model, you have to inform the id in hasMany too:

    public function materials(){
        return $this->hasMany('App\Material' ,'SubCategoria_id');
    }
    

    You should also notice that it would be better if you name yours classes and variables according to Laravel patterns.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题