如何使用模型方法在 laravel 中查詢?我在城市模型中有一個計數器方法,我想在我的選擇查詢中使用它來回應
我怎么寫這個?
我的城市模型
public function mobile()
{
return $this->hasMany(Mobile::class);
}
public function mobile_count()
{
return $this->mobile()->count();
}
我的查詢
public function findCityWithID($id)
{
$subgroup = City::select('id', 'name', 'state_id')->where('state_id', $id)->orderBy('name')->get();
return response()->json($subgroup);
}
我想在 $subgroup 每個 City mobile 計數
uj5u.com熱心網友回復:
該模型:
public function mobiles()
{
return $this->hasMany(Mobile::class);
}
查詢:
$cities = City::withCount('mobiles')->where('state_id', $id)->get();
$response[];
foreach ($cities as $city) {
response[
'id' => $city->id;
'name' => $city->state;
'state_id' => $city->state_id;
'mobile_count' => $city->mobile_count;
];
}
return response()->json($response);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434987.html
