[英]How to access url variable using Slim3 and Eloquent ORM?
我试图摆脱使用Eloquent ORM的困扰,所以我正在使用Slim3 / Twig从头开始创建一个简单的博客。 我已经成功创建了链接到两个表(用户表,发布表)的用户模型和发布模型,并且能够将博客发布链接动态地插入到“ 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
]);
}
}
我在路径中传入了一个变量,因此我可以单击一个博客文章,并使其呈现与正确的“ 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
数组,这是传递给您的route操作的第三个参数:
$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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.