簡體   English   中英

模型 [App\Products] Laravel 沒有查詢結果

[英]No query results for model [App\Products] Laravel

在 laravel5 我收到以下消息(錯誤)

No query results for model [App\Products].

我有一個表“ products ”,其中有一列“ category_id ”,即每個類別項目的category Id 我想根據category Id顯示項目

我的控制器是這樣的

 public function category()
{
 $recordsByCategories=\DB::table('products')
            ->select('categories','category_id', \DB::raw('count(*) as totalProducts'))
            ->groupBy('categories')
            ->get();
 return view('dashboard.show',compact('recordsByCategories'));
 }

**//I have received error in below function**

 public function searchCategoryByTag($id)
        {

         $category_id = Products::findOrFail($id);
         $records=\DB::table('products')->Where('category_id','$category_id');
          dd($records);

        }

我的路線是這樣的

 Route::get('categorys/{id}' ,array(
    'as'=>'category',
    'uses'=>'GoodsController@searchCategoryByTag'));

我的看法是這樣的

@foreach($recordsByCategories as $recordsByCategory)

    <a href="{{URL::route('category',$recordsByCategory->category_id)}}
    " id="search">{{$recordsByCategory->categories}}</a>:{{$recordsByCategory->totalProducts}} 

    @endforeach

檢查您的 API 路由。 確保沒有與該端點競爭會導致/products請求出現 404 錯誤。 這經常發生在我身上。

我知道為時已晚,但是為了您(可能)和其他人的幫助:

在這里你弄錯了'$category_id' ,刪除那個單引號。

public function searchCategoryByTag($id)
{
    $category_id = Products::findOrFail($id);
    $records=\DB::table('products')->Where('category_id', $category_id);
}

如果 $id 等於類別 id,則只執行$records = Products::where('category_id', $id)->get(); 在 searchCategoryByTag 中。

**你應該改變表格**

 $category_id = Products::findOrFail($id);
 $records=\DB::table('products')->Where('category_id','$category_id')->get();

更改為此$records = Products::where('category_id', $id)->get();

`$categroy_id ` 

**是從您的產品表實例中獲取對象 ** $category_id$category_id->id

findOrFail方法將檢索查詢的第一個結果; 但是,如果沒有找到結果,則會拋出Illuminate\Database\Eloquent\ModelNotFoundException 您可以在laravel 文檔的這一部分閱讀更多信息。

Product::findOrFail($id); 此代碼未獲取產品,因此失敗。 考慮使用findfirstget將返回一個數組。

並且您需要從$records=\DB::table('products')->Where('category_id','$category_id');中刪除單引號 ,所以它會變成$records=\DB::table('products')->Where('category_id',$category_id); .

嘗試將此成員添加到您的 Product 模型類;

protected $table = 'products';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM