简体   繁体   English

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

[英]How to access url variable using Slim3 and Eloquent ORM?

I'm trying to get the hang of using Eloquent ORM so I'm creating a simple blog from scratch using Slim3/Twig. 我试图摆脱使用Eloquent ORM的困扰,所以我正在使用Slim3 / Twig从头开始创建一个简单的博客。 I've been successful in creating a User model and Post model that are linked to two tables(user table, post table) and have been able to insert blog post links dynamically into my 'home' twig template. 我已经成功创建了链接到两个表(用户表,发布表)的用户模型和发布模型,并且能够将博客发布链接动态地插入到“ home”树枝模板中。

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 简单的博客列表视图

I've passed in a variable in to my routes so I can click on a blog post and have it render the view that corresponds with the right 'id' 我在路径中传入了一个变量,因此我可以单击一个博客文章,并使其呈现与正确的“ id”相对应的视图

$app->get('/', 'StoryListController:index')->setName('home');

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

but for the life of me I haven't been able to correctly access that variable in my controller. 但是对于我来说,我一直无法在控制器中正确访问该变量。 This is what I've tried, not sure if I was heading in the right direction. 这是我尝试过的方法,不确定我是否朝着正确的方向前进。 Any help to get me going again is appreciated. 任何帮助我再次前进的帮助都将受到赞赏。

<?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
    ]);
  }
}

You can get at the postId from the Request 's attribute: 您可以从Request的属性获得postId

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

or by looking at the array of $args which is the third parameter passed to your route action: 或查看$args数组,这是传递给您的route操作的第三个参数:

$postid = $args['postId'];

Try this: 尝试这个:

<?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
  }
}

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

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