>我从控制器返回 JSON 格式的数据,使用 eloquent 并且工作正常。在一个位置,我需要对数据实现进一步的条件,所以我在 elequent 检索到的数据上实现 where 条件,然后在它上面实现 toJson(( 并返回数据,但数据不是以前的格式。
//in AppCategory model
public function products(){
return $this->hasMany('AppAppProduct','category_id');
}
//in controller
public function category_products($id)
{
$category=AppCategory::where('status', 1)->findorfail($id);
$result=$category->products->where('status',1);
$result->toJson();
return $result;
}
//output
{
"0": {
"id": 13,
"category_id": 1,
"title": "shoe 1",
"description": "test description",
"price": "200",
"status": 1,
"created_at": "2019-09-11 12:33:51",
"updated_at": "2019-09-07 17:00:19"
}
}
//required output (enclosed data into '[]' instead of '{}')
[
"0": {
"id": 13,
"category_id": 1,
"title": "shoe 1",
"description": "test description",
"price": "200",
"status": 1,
"created_at": "2019-09-11 12:33:51",
"updated_at": "2019-09-07 17:00:19"
}
]
您应该使用 get 方法返回集合并将响应返回为 json,因此请将代码更新为:
//in controller
public function category_products($id)
{
$category=AppCategory::where('status', 1)->findorfail($id);
$result=$category->products->where('status',1)->get();
return response()->json($result);
}
您需要返回 json 对象结果:
return $result->toJson();
in AppCategory model
public function products(){
return $this->hasMany('AppAppProduct','category_id')->where('status',1);
}
在控制器中
public function category_products($id)
{
$category=AppCategory::where('status', 1)->findorfail($id);
$result=$category->products;
$result->toJson();
return $result;
}
输出
[
{
"id": 13,
"category_id": 1,
"title": "shoe 1",
"description": "test description",
"price": "200",
"status": 1,
"created_at": "2019-09-11 12:33:51",
"updated_at": "2019-09-07 17:00:19"
}
]
请注意,我仍然对如何在不更改模型的情况下获得所需的结果感到困惑。提前感谢您清除此问题。