在laravel中获得一对多的记录

时间:2015-12-09 18:38:19

标签: php laravel laravel-5 laravel-5.1

我在尝试什么?

获取特定类别及其相关的子类别

类别模型

class Category_Model extends Model
{
    protected $table = "tblcategory";
    protected $primaryKey = "CategoryID";
    public $timestamps = false;

    public function Subcategories()
    {
        return $this->hasMany('\App\Models\Skill\SubCategory_Model');
    }
}

子类别模型

class SubCategory_Model extends Model
{
    protected $table = "tblsubcategory";
    protected $primaryKey = "SubCategoryID";
    public $timestamps = false;
}

行动方法

public function SubCategories($category)
{
    $Categories = \App\Models\Skill\Category_Model
                  ::where("Category", "=", $category)
                  ->Subcategories;
    dd($Categories);
}

当我运行代码时。我得到以下错误

  

SQLSTATE [42S22]:找不到列:1054未知列   'where子句'中的'tblsubcategory.category__model_id'(SQL:select *   来自tblsubcategory tblsubcategorycategory__model_id = 1   和tblsubcategorycategory__model_id不为空)

1 个答案:

答案 0 :(得分:3)

根据评论,您的subcategory表格很可能没有category_model_id,但可能只有category_id。默认情况下,Laravel尝试从模型名称推断外部列的名称(在本例中为Category_Model,其中解释了category_model_id。将类更改为:

class Category_Model extends Model
{
    protected $table = "tblcategory";
    protected $primaryKey = "CategoryID";
    public $timestamps = false;

    public function Subcategories()
    {
        return $this->hasMany('\App\Models\Skill\SubCategory_Model', 'category_id')->get(); // Or whatever the column is actually called
    }
}

应该解决问题。

要同时返回category对象及其subcategories,请将操作代码更改为:

public function SubCategories($category)
{
    $Categories = \App\Models\Skill\Category_Model
                  ::where("Category", "=", $category)
                  ->with("Subcategories")
                  ->first();
    dd($Categories);
} 

$Categories现在还应包含Subcategories对象,可通过$Categories->Subcategories访问,该对象应返回Subcategory个对象的集合。如果你想看到每一个,你可以使用foreach

进行循环
foreach($Categories->Subcategories AS $Subcategory){
  echo $Subcategory->name;
  // etc etc.
}