【发布时间】:2021-08-28 14:03:07
【问题描述】:
美好的一天。就像我在这篇文章Using Query Builder and MySql to get categories and sub - categories 中解释的那样,我想从这张表中做出一些有意义的事情。我决定走 Eloquent 的方式。我能够得到不同的类别,如下所示。我如何遍历属于特定类别的每个标题? 例如,以如下形式获取:
CatA
Title 1
Title 5
猫B
Title 2
Title 3
Title 4
我的代码如下所示
public function type(Request $request){
$details = [];
$categories = Category::distinct()->get(['category']); //Get the distinct categories from the category column in the table
foreach($categories as $category){
$titles = Category::where('type',$category->type);
$details = ['cat'=>$category->type,[
'title' => $titles->title,
'pk' => $titles->pk
]];
}
return response()->json([
"Data" => $details
]);
}
没有得到结果。请问有没有更好的方法可以做到这一点?
【问题讨论】:
-
我会使用两个模型
Category和Title。否则你的模型会有点混乱。 -
您使用显示的代码得到什么结果?看来你需要的是一个 gruopBy
标签: php arrays laravel loops eloquent