尝试从表中检索来自分类表的帖子

时间:2018-12-12 23:33:43

标签: laravel laravel-blade

您好,我正在尝试循环搜索与该类别相关的帖子。当我使用id时它可以工作,但是当我更改控制器功能以按段搜索时,它会检索段但不会加载foreach循环。

我尝试了很多方法,但我不知道我要去哪里错,请帮忙。

类别模型:

protected $table = 'post_categories';
public function posts()
{
    return $this->hasMany('App\Post', 'id', 'name', 'catslug');
}

帖子模型

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

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

控制器

public function getPostCategory($catslug) {        
    $postCategories = PostCategory::with('posts')
                    ->orderBy('name', 'asc')
                    ->where('catslug', '=', $catslug)
                    ->first();
     return view ('articles.category.categoriesposts')->with('postCategories', $postCategories);
}

路线

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

查看

@foreach($postCategories->posts as $post)
  <h4>{{ substr($post->title, 0, 50) }}</h4>
   <p>{{ substr($post->body, 0, 90) }}</p>             
 @endforeach

当我使用id时,没有问题,我看不到我在做错什么,任何反馈都会得到真正的赞赏

谢谢

1 个答案:

答案 0 :(得分:0)

将类别ID保存在由类别名称或子弹插入的帖子表中。

帖子类别模型的更改:

public function posts()
    {
        return $this->hasMany('App\Post', 'category_id');
    }

您的控制器方法:

public function getPostCategory($catslug)
    {
        $postCategories = PostCategory::with('posts')->where('catslug', $catslug)->first();
        return view('articles.category.categoriesposts')->with('postCategories', $postCategories);
    }

如果您想按名称订购帖子,则在关系中添加orderBy()

public function posts()
    {
        return $this->hasMany('App\Post', 'category_id')->orderBy('name', 'asc');
    }
相关问题