我有三个表:
SELECT COUNT(*) as Total
FROM users_personals p
INNER JOIN users u
ON u.id = p.user_id
AND u.status NOT IN (1,2,7)
WHERE
p.neighborhoods = 'Miami Beach'
p.created_at >= '2018-04-01'
我有三个模型类别,子类别
1)=>类别模型代码
categories table fields id, category_name
subcategories table fields id, category_id, subcategory_name
child_categories table fields id, category_id, subcategory_id, child_category_name
2)=>子类别模型代码
class Category extends model {
public function subcategory(){
return $this->hasMany(Subcategory::class);
}
public function Child_category(){
return $this->hasMany(Child_category::class);
}
}
3)=> Child_category模型代码
class Subcategory extends model {
public function Category(){
return $this->belongsTo(Category::class);
}
}
如何建立雄辩的关系,以从child_categories表中查找具有相关类别和子类别名称的所有数据?
答案 0 :(得分:1)
一旦定义了关系,就可以通过简单地调用与所需关系同名的属性来获取它们。
$category = Category::first();
$subcategory = $category->subcategory;
如果您希望将所有类别以及所有子类别和子类别归为一类,则可以使用with()
方法来急于有效地加载它们。
$categories = Category::with(['subcategory', 'Child_category'])->get();
这将获取所有类别,然后获取所有相关的子类别和子类别并适当地关联它们。