[英]Select by name in laravel 5.6 api
我的數據庫中有很多廣告,我想按名稱嘗試從主題中選擇一個,但返回的結果為空
public function index()
{
# code...
// $Ads = ads::all();
// return $this->sendResponse($Ads->toArray(), 'Ads read succesfully');
$column = 'name'; // This is the name of the column you wish to search
$Ads = ads::where($column)->first();
return response()->json(['success'=> true,'ads'=>$Ads, 'message'=> 'Ads read succesfully']);
}
這就是我在郵遞員中得到的:
{“ success”:true,“ ads”:null,“ message”:“廣告讀取成功”}
在深入研究之前,需要注意一些事項:
您需要具有Request變量,以便可以獲取用戶輸入,或者如果它是靜態的,則只需將其提供為靜態。 但是,static沒有意義,因此我提供了將使用輸入變量的代碼。
您需要將值與列名進行比較才能獲取它。
模型名稱應為單數形式,並以大寫字母開頭,與類名稱相同,因此您應使用廣告代替廣告,廣告適合表名,而不適合模型名。
考慮以上注意事項,以下代碼將為您服務:
public function index(\Illuminate\Http\Request $request)
{
# code...
$column = 'name'; // This is the name of the column you wish to search
$columnValue = $request->input('name');// This is the value of the column you wish to search
$Ads = Ad::where($column, $columnValue)->first();
return response()->json(['success'=> true,'ads'=>$Ads, 'message'=> 'Ads read succesfully']);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.