0

我有一个JsonResource应该Post返回一个帖子。但是在加入其他一些数据后,我得到了这个错误:array_merge_recursive(): Argument #2 is not an array

不起作用

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($slug)
{
    // $post = Post::findOrFail($id);
    $post = Post::where('slug', $slug)->first();
    // return single post as resource
    return new PostResource($post);
}

当我直接 return 时$posts,我得到了一个 json ,几乎没问题。但它不包含连接的数据comment

这里是class Post extends JsonResource.

public function toArray($request)
{
    // return parent::toArray($request);
    $img = '.'.pathinfo('storage/'.$this->image, PATHINFO_EXTENSION);
    $imgName = str_replace($img,'', $this->image);
    $img = $imgName.'-cropped'.$img;

    return [   
        'id' => $this->id,
        'title' => $this->title,
        'body' => $this->body,
        'excerpt' => $this->excerpt,
        'image' => asset('/storage/' . $this->image),
        'image_small' => asset('storage/' . $img),
        'author_id' => $this->author_id,
        'category_id' => $this->category_id,
        'seo_title' => $this->seo_title,
        'slug' => $this->slug,
        'meta_description' => $this->meta_description,
        'meta_keywords' => $this->meta_keywords,
        'status' => $this->status,
        'featured' => $this->featured,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'user' => User::find($this->author_id),
        'commentCount' => $this->comment->where(['status' => 1, 'id_post' => $this->id])->count(),
    ];
}

// **Big mistake below here**:
public function with($request)
{
    // return [
    //     'version' => '1.0.0',
    // ];
}

模型:

class Post extends Model
{
    public $primary_key = 'id';
    public $foreign_key = 'id_post';

    public function user()
    {
        return $this->belongsTo('App\User', 'id_author', 'id');
    }

    public function comment()
    {
        return $this->belongsTo('App\Comment', 'id', 'id_post');
    }
}

为什么我会收到有关 array_merge_recursive() 的警告?

4

1 回答 1

4

我不想重现您的代码的问题,但是-您确定包含所有内容吗?查看https://laravel.com/docs/5.6/eloquent-resources#writing-resources可以定义额外的数据数据也将像这样返回:

/**
 * Get additional data that should be returned with the resource array.
 *
 * @param \Illuminate\Http\Request  $request
 * @return array
 */
public function with($request)
{
    return [
        'meta' => [
            'key' => 'value',
        ],
    ];
}

Post因此,当我将以下方法添加到此资源类时,我能够重现该问题:

public function with($request)
{
    return 'test';
}

如您所见,它仅返回字符串而不是数组,然后我遇到了与您相同的错误。

但是当我根本没有实现这个方法或者当我只返回一个数组时,一切都很好。

所以总结一下 - 确保你没有with定义返回数组以外的东西的方法。

于 2018-08-27T19:18:30.770 回答