【问题标题】:How in Laravel 7 resources show only some fields of a creator?Laravel 7 中的资源如何只显示创作者的某些领域?
【发布时间】:2020-04-29 15:15:39
【问题描述】:

在我的 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'),
            ...

如果我只需要在上面显示创建者的某些字段,如何定义?

已编辑:

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')

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

谢谢!

【问题讨论】:

  • This 解决方案可能会做你想做的事,你可以为创建者创建一个新资源,然后在你的 VoteResource 中调用它

标签: php laravel eloquent resources laravel-7


【解决方案1】:

我认为你有两个选择。

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

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

  1. 选择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,因为它负责加入这两个字段。

【讨论】:

  • 我尝试:$activeVotes = Vote ::getByStatus('A') ->with('voteCategory') ->with(['creator' => function ($query) { $query- >select('first_name', 'last_name', 'website'); }]) ->get();结果“创建者”为空
  • 你能把你的Vote 模型显示在哪里吗?投票和创作者是如何联系起来的?用外键分隔表?只需编辑您的问题并插入格式正确的所需信息。
  • 请看已编辑
  • 您需要选择 id 字段,因为该字段将 votesusers/creators 连接起来。我更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 2017-06-12
  • 2012-04-07
相关资源
最近更新 更多