显示属于Laravel中类别的帖子

时间:2019-05-23 10:47:37

标签: php laravel laravel-blade

我正在尝试获取属于每个类别的帖子,我以前曾从事过此工作,但在这里似乎找不到我做错了什么。

我有一个发布表和一个类别表

路线

Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController@getPostCategory']);

控制器

public function getPostCategory($id)
{
    $postCategories = PostCategory::with('posts')
        ->where('post_category_id', '=', $id)
        ->first();

    $categories = PostCategory::all();

    // return view
    return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}

查看

@foreach($postCategories->posts as $post)

    <div class="well">

        <div class="media">
            <a class="pull-left" href="#">
                <img class="media-object" src="http://placekitten.com/150/150">
            </a>

            <div class="media-body">
                <h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
                <p class="text-right">By Francisco</p>
                <p>{{ substr($post->body, 0, 90) }}</p>
                <ul class="list-inline list-unstyled">

                </ul>
            </div>
        </div>
    </div>

@endforeach

POST MODAL

public function postCategory()
{   
    return $this->belongsTo('App\PostCategory');
}

POSTCATEGORY MODAL

class PostCategory extends Model
{
    // connect Categories to Posts tables
    protected $table = 'post_categories';

    // Category belongs to more than 1 post
    public function posts()
    {
        return $this->hasMany('App\Post', 'post_category_id');
    }
}

每次进入显示的类别我都看不到自己在做什么

  

试图获取非对象的属性

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

替换您的行:

$postCategories = PostCategory::with('posts')       
             ->where('post_category_id', '=', $id)
             ->first();

具有:

    $postCategories = PostCategory::find($id)->posts;

将您的PostCategoryModel中的行更改为:

return $this->hasMany('App\Post', 'post_category_id','post_category_id');