我在尝试什么?
获取特定类别及其相关的子类别
类别模型
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
tblsubcategory
。category__model_id
= 1 和tblsubcategory
。category__model_id
不为空)
答案 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.
}