如何使用 Slim3 和 Eloquent ORM 访问 url 变量?

How to access url variable using Slim3 and Eloquent ORM?

我正在尝试掌握使用 Eloquent ORM 的窍门,所以我正在使用 Slim3/Twig 从头开始​​创建一个简单的博客。我已经成功地创建了一个 User 模型和 Post 模型,它们链接到两个 tables(user table, post table) 并且已经能够将博客 post 链接动态插入到我的 'home' twig 模板中。

namespace App\Controllers;

use App\Models\User;
use App\Models\Post;
use Slim\Views\Twig as View;
use Illuminate\Database\Eloquent\Model;

class StoryListController extends Controller
{
  public function index($request, $response)
  {
    $posts = Post::join('users', 'posts.user_id', '=', 'users.id')->get();

    return $this->container->view->render($response, 'home.twig', [
      'posts' => $posts
    ]);
  }
}

Simple Blog list view

我已经将一个变量传递到我的路由中,这样我就可以点击一个博客 post 并让它呈现与右侧 'id'

对应的视图
$app->get('/', 'StoryListController:index')->setName('home');

$app->get('/stories/story/{postId}', 'StoryTemplateController:story')->setName('stories.story');

但我一直无法在我的控制器中正确访问该变量。这是我尝试过的,不确定我是否朝着正确的方向前进。感谢任何帮助我重新开始的帮助。

<?php

namespace App\Controllers;

use App\Models\User;
use App\Models\Post;
use Slim\Views\Twig as View;
use Illuminate\Database\Eloquent\Model;

class StoryTemplateController extends Controller
{
  public function story($request, $response, $postId)
  {
    $post = Post::join('users', 'posts.user_id', '=', 'users.id')->where('posts.id', '=', '{postId}')->with(['postId' => $postId])->get();
    return $this->container->view->render($response, '/stories/story.twig', [
      'post' => $post
    ]);
  }
}

您可以从 Request 的属性获取 postId

$postId = $request->getAttribute('postId');

或者通过查看 $args 的数组,这是传递给您的路由操作的第三个参数:

$postid = $args['postId'];

试试这个:

<?php

namespace App\Controllers;

use App\Models\User;
use App\Models\Post;
use Slim\Views\Twig as View;
use Illuminate\Database\Eloquent\Model;

class StoryTemplateController extends Controller
{
  public function story($request, $response, $args)
  {
    $postId = $requst->getAttribute('postId');
    // or $postId = $args['postId'];

    // rest of method
  }
}