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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?