【问题标题】:Display posts belonging to category in laravel在 laravel 中显示属于类别的帖子
【发布时间】:2019-05-23 20:54:49
【问题描述】:

我正在尝试获取属于每个类别的帖子,我之前有这个工作,但我似乎无法在这里找到我做错了什么。

我有一个帖子表和一个类别表

路线

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

后模态

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

后类别模式

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');
    }
}

每次转到它显示的类别时,我都看不到我做错了什么

试图获取非对象的属性

任何帮助将不胜感激,谢谢

【问题讨论】:

  • 也许这个分类没有任何帖子?在 with('posts') 之前使用 whereHas('posts')
  • 哪一行导致错误?
  • 不,这不是问题,我认为我在其他地方有一个错误,它会引发错误。试图获取非对象的属性(查看:/Users/macpro/sites/sixmedia/resources/views/pages/frontend/articles/single.blade.php)
  • 能否请您在您的刀片文件中dd($post); 以便我们查看您是否成功调用帖子?
  • 我不知道为什么会抛出这个错误,因为我没有尝试访问 getSingle 函数

标签: php laravel laravel-blade


【解决方案1】:

替换你的行:

$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');

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2016-05-28
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    相关资源
    最近更新 更多