【发布时间】: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