簡體   English   中英

如何使用Slim3和Eloquent ORM訪問url變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM