美好的一天。就像我在这篇文章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
【参考方案1】:
您可以与帖子和类别建立多对多关系。然后获取所有类别的帖子。
例子:
$categories = Category::with('posts')->all();
然后您可以循环浏览类别和帖子
foreach($categories as $category)
foreach($category->posts as $post)
echo $post->title;
文档:https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
【讨论】:
谢谢。我试过这个,但它不起作用,因为类别必须首先是不同的。 $categories = Category::with('posts')->distinct()->get(['type']);正在为帖子返回一个空数组 $categories = Category::with('posts')->distinct()->get(['type']);正在为帖子返回一个空数组