Laravel将数据添加到集合

时间:2019-07-19 22:29:59

标签: php laravel orm eloquent

我想将注释元素添加到响应数据,但仅添加到某些端点。 文章模型:

Arrays.asList(new ArrayList<>())

文章资源:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table = 'articles';

    protected $primaryKey = 'idArticle';

    protected $fillable = [
        'idArticle', 'Topic', 'Image', 'Content', 'Views', 'Visible', 'Main'
    ];

    public function category()
    {
        return $this->hasOne(Categories::class);
    }

    public function user()
    {
        return $this->hasOne(User::class);
    }

    public function comments() {
        return $this->hasMany(Comments::class)
            ->where('Visible', 1)
            ->where('idSubReference', 0)
            ->orderBy('created_at', 'desc');
    }
}

我想将评论中的数据添加到响应中,但仅添加到特定的数据端点(返回文章完整数据的人)。我尝试添加:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class Article extends Resource
{
    public function toArray($request)
    {
        return [
            'idArticle' => $this->idArticle,
            'category' => $this->category->Name,
            'user' => new User($this->user),
            'title' => $this->Title,
            'image' => $this->Image,
            'content' => $this->Content,
            'views' => $this->Views,
            'visible' => $this->Visible,
            'main' => $this->Main,
            'created' => $this->created_at,
            'modified' => $this->updated_at,
        ];
    }
}

添加到资源,但是每次调用它时它都会添加注释。因此,我只将注释添加到称为/ articles / {id} / details的endopint中 获取文章数据的示例:

'comments' => Comments::collection($this->comments)

1 个答案:

答案 0 :(得分:0)

您可以这样做。

为您的路线命名:

Route::get('/articles/{id}/details','YourController@method')->name('articles.details');

修改资源toArray()方法:

public function toArray($request)
{
    // store response in array
    $response = [
        'idArticle' => $this->idArticle,
        'category' => $this->category->Name,
        'user' => new User($this->user),
        'title' => $this->Title,
        'image' => $this->Image,
        'content' => $this->Content,
        'views' => $this->Views,
        'visible' => $this->Visible,
        'main' => $this->Main,
        'created' => $this->created_at,
        'modified' => $this->updated_at,
    ];

    // check the current route name and append comments if applicable
    if (Route::currentRouteName() === 'articles.details') {
        $response['comments'] = Comments::collection($this->comments);
    }

    return $response;
}