1

我有以下关系定义:

邮政:

class Post extends Model
{
  use SoftDeletes;

  protected $fillable = ['title','content','category_id','featured_image','slug'];
  protected $dates = ['deleted_at'];

  public function category()
  {
    return $this->belongsTo('App\Category');    
  }

  public function tags()
  {
    return $this->belongsToMany('App\Tag')->withTimestamps();
  }

}

类别:

class Category extends Model
{

  public function posts()
  {
    return $this->hasMany('App\Post');
  }
}

在我的控制器的索引函数中,我试图获得前 3 个类别(就帖子数量而言)及其前 3 个最新帖子。我做了以下工作,只要我不包括内部采取方法:

$cats_and_posts = Category::with(['posts'=>function($query){
        $query->orderBy('updated_at','desc')->take(3)->get();
    }])->withCount('posts')->orderBy('posts_count','desc')->take(3)->get();

如果我包含内部获取方法,则某些类别将加载空帖子关系。这是 dd 为“cats_and_posts”变量生成的内容:

 #items: array:3 [▼
0 => Category {#261 ▶}
1 => Category {#260 ▶}
2 => Category {#243 ▼
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:5 [▶]
  #original: array:5 [▶]
  #relations: array:1 [▼
    "posts" => Collection {#269 ▼
      #items: []
    }
  ]
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: true
  +wasRecentlyCreated: false
}
]
}

如果没有内部 take 方法,所有类别的帖子都在加载!

非常感谢一些帮助。无法弄清楚为什么会这样。

4

1 回答 1

0

无需->get()在关系的子查询中添加 a。

$cats_and_posts = Category::with([
        'posts' => function ($query) {
            $query->orderBy('updated_at', 'desc')
                ->take(3);
        }
    ])
    ->withCount('posts')
    ->orderBy('posts_count', 'desc')
    ->take(3)
    ->get();
于 2017-08-10T10:22:24.527 回答