簡體   English   中英

Laravel API 加載時的資源集合

[英]Laravel API ResourceCollection WhenLoaded

我嘗試在我的資源數組中包含一個關系,如果它已經被急切加載,但沒有讓它工作。

任何人都有想法,我如何檢查 ResourceCollection 中的關系?

數據庫架構如下所示: 在此處輸入圖像描述

這是我的帖子 Model

class Post extends Model
{
    function categories() {
        return $this->belongsToMany('App\Category');
    }
}

這是我的類別 Model

class Category extends Model
{
    function posts() {
        return $this->belongsToMany('App\Post');
    }
}

這是我的帖子 Controller

Class PostController extends Controller
{
    public function index()
    {
        return new PostResourceCollection(Post::with("categories")->get());
    }
}

這是我的 Post ResourceCollection

class PostResourceCollection extends ResourceCollection
{
    public function toArray($request)
    {

        return [
            'data' => $this->collection->transform(function($page){
                return [
                    'type' => 'posts',
                    'id' => $page->id,
                    'attributes'    => [
                        'name' => $page->title,
                    ],
                ];
            }),
            //'includes' => ($this->whenLoaded('categories')) ? 'true' : 'false',
            //'includes' => ($this->relationLoaded('categories')) ? 'true' : 'false',
        ];
    }
}

可能為時已晚,下面的解決方案是針對這種情況的解決方法:

return [
    ...,
    'includes' => $this->whenLoaded('categories', true),
];

加載自定義屬性:

return [
    ...,
    'includes' => $this->whenLoaded('categories', fn() => $this->categories->name),
];

您的關系是錯誤的, 一個帖子屬於許多類別,一個類別有很多帖子,因此請更改:

class Category extends Model
{
    function posts() {
        return $this->belongsToMany('App\Post', 'category_post');
    }
}

class Category extends Model
{
    function posts() {
        return $this->hasMany('App\Post', 'category_post');
    }
}

現在,當您加載帖子時,您還可以加載類別:

$posts = Post::with('categories')->get();

知道了。那是丟失的那一塊。 如果有人對此有更好的解決方案,將不勝感激。

      foreach ($this->collection as $item) {
          if ($item->relationLoaded('categories')) {
              $included = true;
          }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM