在 Laravel 7 资源中如何只显示创建者的某些字段?

How in Laravel 7 resources show only some fields of a creator?

在我的 Laravel 7.6 应用程序中,我使用了检索到创建者的资源集合 在某些情况下,我希望不显示所有创建者字段,而只显示其中的一些。我有我的控制权:

$activeVotes = Vote
    ::getByStatus('A')
    ->where('votes.id', 1) 
    ->with('voteCategory')
    ->with('creator')
return (new VoteCollection($activeVotes));

在 app/Http/Resources/VoteCollection.php 我有 :

<?php

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;

class VoteCollection extends ResourceCollection
{
    public static $wrap = 'votes';

    public function toArray($request)
    {

        $this->collection->transform(function ($votes) {
            return new VoteResource($votes);
        });

        return parent::toArray($request);
    }
}

并在 app/Http/Resources/VoteResource.php 中:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class VoteResource extends JsonResource
{

    public static $wrap = 'votes';
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'creator' => $this->whenLoaded('creator'),
            ...

如果只显示上面creator的部分字段,如何定义?

已编辑:

My app/User.php has :

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use DB;
...
class User extends Authenticatable implements MustVerifyEmail
{
    use Billable;
    use HasApiTokens, Notifiable;
    use funcsTrait;
    protected $table = 'users';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $userAvatarPropsArray = [];
    protected $avatar_filename_max_length = 255;
    protected $full_photo_filename_max_length = 255;
    protected static $password_length = 8;

    protected $fillable = [ 'username', 'email', 'status', 'provider_name', 'template_id', 'provider_id', 'first_name', 'last_name', 'phone', 'website', 'password',
    'activated_at', 'avatar', 'full_photo', 'updated_at', 'verified' ];

    protected $hidden = [ 'password', 'remember_token'  ];
    ...

    public function votes()
    {
        return $this->hasMany('App\Vote', 'creator_id', 'id');
    }
    ...

和app/Vote.php :

<?php

namespace App;

use DB;
use App\MyAppModel;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Http\Traits\funcsTrait;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Validation\Rule;

class Vote extends MyAppModel
{
    use funcsTrait;
    use Sluggable;
    use HasTags;

    protected $table = 'votes';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $casts = [
        'meta_keywords' => 'array'
    ];

    protected $fillable = ['name', 'slug', 'description', 'creator_id', 'vote_category_id', 'is_quiz', 'status', 'image'];
    protected static $logAttributes = ['*'];
    ...
    public function creator(){
        return $this->belongsTo('App\User', 'creator_id','id');
    }

在投票和用户模型中引用了其他模型。 否则

   ->with('creator')

不起作用。 有没有我错过的选项?

谢谢!

我想你有两个选择。

  1. 在您的 user 模型上使用 hidden

通过使用 hidden,请参阅 Laravel 文档,您可以指定在模型的 JSON 或 Arrray 表示中显示哪些字段。

  1. Select 您的 with 语句中的字段
$activeVotes = Vote::getByStatus('A')->where('votes.id', 1) 
                                     ->with('voteCategory')
                                     ->with(['creator' => function ($query) {
                                         $query->select('id', 'first_name');
                                     }]);

return (new VoteCollection($activeVotes));

您需要包含字段 id,因为它负责连接这两个字段。