簡體   English   中英

Laravel 中此集合實例上不存在屬性 [name]

[英]Property [name] does not exist on this collection instance in Laravel

我正在嘗試查看特定帖子或 ID 的詳細信息。 但它拋出錯誤。 注意:我想使用get()而不是first()

錯誤:

此集合實例上不存在屬性 [名稱]。 (查看:C:\\xampp\\htdocs\\myBlog\\resources\\views\\post\\viewPost.blade.php)

1.allPostView.blade.php

a href="{{ URL::to('view/post/'.$row->id) }}"

2.web.php

Route::get('view/post/{id}','PostController@viewPost');

3. PostControler.php [查看/閱讀帖子(特定帖子或的詳細信息視圖)]

public function viewPost($id){
    $post=DB::table('posts')
    ->join('categories','posts.category_id','categories.id')
    ->select('posts.*','categories.name')
    ->where('posts.id',$id)
    ->get();

    //return response()->json($post);
    return view('post.viewPost', compact('post'));
}

4. viewPost.blade.php最終查看頁面

Category name: {{ $post->name }}

{{ $post->title }}

img src="{{URL::to($post->image)}}" style="height: 200px; width:400px;"

{{ $post->details }}
  1. 但是當我使用return response()->json($post); 它按預期給了我數據。 喜歡:

在此處輸入圖片說明

get()方法返回一個 Collection,它是Laravel數組的對象包裝器。 由於您在 id 上有一個 where 子句,您需要一個單一的對象,您可以使用first()來代替。

$post = DB::table('posts')
    ->join('categories', 'posts.category_id', 'categories.id')
    ->select('posts.*', 'categories.name')
    ->where('posts.id', $id)
    ->first();

替代方案

即使你的解決方案是非常理想的,在Laravel還有一個更實用的處理關系的解決方案。

定義你的關系。

class Post {
    public function category() {
        return $this->belongsTo(Category::class);
    }
}

現在在執行查詢之前預先加載類別。

$post = Post::with('category')->find($id);

在您看來,您可以在相當優化的查詢執行計划中通過關系簡單地訪問類別名稱。 同時,您的代碼更具可讀性和可維護性,在我看來,這是Laravel正確的做法。

{{ $post->category->name }}

暫無
暫無

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

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