【问题标题】:Refactor 3 parent child category relation queries with whereHas or another type of query?使用 whereHas 或其他类型的查询重构 3 个父子类别关系查询?
【发布时间】:2019-01-09 13:41:41
【问题描述】:

所以我有具有以下关系的类别和频道表。一个类别有很多渠道。我要做的是获取属于父母子类别的所有频道。我目前有一个工作尝试(控制器中的尝试 2),我想知道我是否可以将它变成一个查询?

频道类别

$table->increments('id');
$table->string('name');
$table->string('slug');
$table->integer('parent_id')->default(null);

频道

$table->increments('id');
$table->string('name');
$table->string('slug');
$table->integer('category_id');

按类别 Slug Route 获取所有频道

Route::get('/{channelCategory}', 'ChannelController@index');

频道控制器

public function index($channelCategory)
{

         //Attempt 1. This works perfectly fine, but would like it to be in one query if possible
        /*if($channelCategory->parent_id === 0){
            $categories = ChannelCategory::where(['parent_id' => $channelCategory->id])->pluck('id');
            $channels = Channel::whereIn('category_id', $categories)->get();
        } else {
            $channels = $channelCategory->channels;
        }*/

         //Attempt 2 whereHas Query. 
         //The problem is that it gets all posts from all parent categories instead of just one.
        /*$channels = Channel::whereHas('category', function ($query) use ($channelCategory) {
            $query->where('parent_id', $channelCategory->parent_id);
            $query->orWhere('parent_id', null);

         })->get(); */



    return view('channels.home', compact('channels'));
}

也许我正在尝试做的事情对于 whereHas 是不可能的。是否可以在一个查询中进行第二次尝试,如果可以,如何?

【问题讨论】:

  • 我在问你的代码,什么包含 $channelCategory ?它是一个对象还是只是一个字符串?为什么$channelCategory->id
  • 它是一个对象。因此,当我向路由发送请求时,它会在控制器的 index 方法中自动更新 ChannelCategory $channelCategory
  • 抱歉。那应该是$channelCategory->slug 只是看着我认为这是我更改的一段无用的代码,并试图用来找出我进一步删除的问题。对此感到抱歉。

标签: laravel laravel-5 eloquent


【解决方案1】:

我认为您可以通过预先加载频道然后将类别频道映射在一起来做到这一点:

$categories = ChannelCategory::with('channels')
                             ->where('parent_id', $channelCategory->id)
                             ->get();

return view('channels.home', [
    'channels' => $categories->flatMap->channels
]);

可能需要使用 LengthAwarePaginator 类手动完成分页:

$page = $request->get('page', 1);
$perPage = $request->get('perPage', 15);
$channels = $categories->flatMap->channels;
$items = $channels->forPage($page, $perPage);

$paginator = new LengthAwarePaginator($items, $channels->count(), $perPage, $page);

获取最新将涉及对集合进行排序并获取所需的限制:

$limit = $request->get('limit', 10);
$latest = collect($categories->flatMap->channels)->sortByDesc('created_at')->take($limit);

【讨论】:

  • 这是有效的,但不能使用 latest() 或分页频道。有什么办法可以做到吗?
猜你喜欢
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
相关资源
最近更新 更多