不显示模型字段

Model fields not displayed

我有一篇文章 table,其中包含图像、category_id、created-by、updated_by、created_at、updated_at 字段。我将文章翻译存储在一个单独的 table 中,其中包含 slug、标题、副标题、描述、区域设置字段。

我想使用 seo 友好的 url,例如 articles/category-slug/article-slug

我在 ArticeController 中尝试了下面的代码

public function show(ArticleCategory $articlecategory, $slug)
{
    $locale = Lang::locale();
    $article = Article::join('article_translations', 'articles.id', '=', 'article_translations.article_id')
    ->where([['slug', $slug], ['locale', $locale]])->with('category')
    ->firstOrFail();
    $article->addPageView();
    return ArticleResource::collection($article);
}

old-question(由 Chris answer 解决):但它不显示所有字段

我已经根据 Chris 的建议更新了上面的代码。但是我也在使用资源 collection 并且上面的代码显示错误。 错误

Method Illuminate\Database\Query\Builder::mapInto does not exist.

文章资源

<?php

namespace App\Http\Resources\Articles;

use Illuminate\Http\Resources\Json\JsonResource;
use Carbon\Carbon;
use App\Models\ArticleTranslation;

class ArticleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
          'id' => $this->id,
          'article_url' => '/articles/'.$this->category->slug.'/'.$this->slug,
          'category' => $this->category->name,
          'category_slug' => $this->category->slug,
          'category_url' => '/articles/'.$this->category->slug,
          'image' => url('/').$this->image,
          'author' => $this->creator->name,
          'created' => Carbon::parse($this->created_at)->diffForHumans(),
          'updated' => Carbon::parse($this->updated_at)->diffForHumans(),
          'views' => $this->page_views,
          'title' => $this->title,
          'subtitle' => $this->subtitle,
          'description' => $this->content,
          'links' => [
              'self' => 'link-value',
          ],
        ];
    }
}

您正在使用 select 打开仅针对 idslug 的查询,因此您将始终被限制在这些字段中。

尝试:

$locale = Lang::locale();
        $article = Article::join('article_translations', 'articles.id', '=', 'article_translations.article_id')
        ->where('slug', $slug)->withTranslations($locale)
        ->firstOrFail();
        $article->addPageView();
        return $article;