简体   繁体   English

Laravel 5:如何检索和显示属于某个类别的所有帖子

[英]Laravel 5: how can I retrieve and display all posts that belong to certain category

I have 3 tables我有3张桌子

user:       id, username
subreddits: id, name, created_at
posts:      id, title, link, user_id, subreddit_id

The problem is, I am fetching the id of the subreddit / category manually while I need to be fetching it dynamically.问题是,当我需要动态获取它时,我正在手动获取 subreddit / 类别的 id。 How can I achieve that?我怎样才能做到这一点?

This is the show() method in SubredditController.php这是 SubredditController.php 中的show()方法

public function show(Subreddit $subreddit)
    {

        $posts = Subreddit::findOrFail(3)->posts()->get();

        return view('subreddit/show')->with('subreddit', $subreddit)
                                    ->with('posts', $posts);
    }

And this is Subreddit Model这是 Subreddit 模型

class Subreddit extends Model
{
    protected $fillable = [
        'name',
        'description'
    ];

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

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

routes.php路由文件

Route::resource('subreddit', 'SubredditController');
Route::resource('posts', 'PostsController');

RouteServiceProvider.php路由服务提供者.php

$router->model('articles', 'App\Article');
$router->model('subreddit', 'App\Subreddit');
$router->model('posts', 'App\Post');

As you are using Route Model Binding, Laravel will automatically retrieve an object for the $id provided in the URI, which can then be injected into your method as an argument using dependency injection.当您使用路由模型绑定时,Laravel 将自动检索 URI 中提供的 $id 的对象,然后可以使用依赖注入将其作为参数注入到您的方法中。

public function show(Subreddit $subreddit){ ... }

You can access the data as you would any object.您可以像访问任何对象一样访问数据。 Eg To access the id of the record you can use $subreddit->id .例如,要访问记录的 id,您可以使用$subreddit->id

public function show(Subreddit $subreddit)
{
    $posts = Subreddit::findOrFail($subreddit->id)->posts()->get();

    return view('subreddit/show')->with('subreddit', $subreddit)
                                    ->with('posts', $posts);
}

I'm fairly new with Laravel, but I think you need to define a route with parameters (sorry if I misunderstood your question).我对 Laravel 还很陌生,但我认为您需要定义一个带有参数的路由(对不起,如果我误解了您的问题)。

http://laravel.com/docs/5.1/routing#route-parameters http://laravel.com/docs/5.1/routing#route-parameters

You need to pass the id using your route.您需要使用您的路线传递 id。

In your routes.php file, you can have this:在你的 routes.php 文件中,你可以有这个:

Route::get('subreddit/{id}', 'SubredditController@show');

And in SubredditController.php, pass the id to your method, like this:在 SubredditController.php 中,将 id 传递给您的方法,如下所示:

public function show($id)
{
    $subreddit = Subreddit::findOrFail($id);
    $posts = $subreddit->posts()->get();

    return view('subreddit/show')->with('subreddit', $subreddit)
                                 ->with('posts', $posts);
}

Why you are typing the model to the parameter of the function?为什么要在函数的参数中键入模型?

show(Subreddit $subreddit)

I saw it somewhere, but I cannot remember the need to use it.我在某处看到它,但我不记得需要使用它。

are you using the column id autoincrement in the database?, if not, you have to especify it in the model adding the property incrementing and set it to false您是否在数据库中使用列id自动增量?如果没有,您必须在模型中指定它添加属性增量并将其设置为 false

public $incrementing = false;

and specify the actual primarykey并指定实际的主键

protected $primaryKey = 'code';

With the configuration that you posted, this code works for me:使用您发布的配置,此代码适用于我:

routes.php路由文件

Route::resource('subreddit', 'SubredditController');

SubredditController.php子目录控制器.php

public function show($id)
{
    $subreddit = Subreddit::findOrFail($id);
    $subreddit->load('posts');
    return view("subreddit/show")->with("subreddit", $subreddit);
}

url网址

http://localhost:8888/test/public/subreddit/1

I'm loading the relation in the same object so send only one param to the view我在同一个对象中加载关系,所以只向视图发送一个参数

I think what you want here is route model binding我认为你在这里想要的是路由模型绑定

If you are using laravel 5, jeff way happens to have a very good tutorial for ithere如果您使用的是 laravel 5,jeff way 恰好有一个非常好的教程here

here is also the documentation for route model binding.这里也是路由模型绑定的文档。

Good news is Route model Binding is also flexible, even binding a complex data subset from your model to the route.好消息是路由模型绑定也很灵活,甚至可以将复杂的数据子集从模型绑定到路由。 which i think will fit your need.我认为这将适合您的需要。

Fetch category with all posts获取所有帖子的类别

$categories = Subreddit::with('posts') -> where('id',$id) -> first(); 
if (categories){
  $data['results'] = categories;
}else{
  $data['results'] = null;
}

return view('myview') -> with($data);

The variable $results will be accessible in your view.您可以在视图中访问变量$results In your view在你看来

if (!is_null($results){
  foreach($results as $result){
    // do something.
  }
} 

Hooe this help.呼这个帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM