mercredi 1 août 2018

Refactor 3 parent child category relation queries with whereHas or another type of query?

So I have categories and channels table with a following relationship. A category hasMany channels. What I'm trying to do is get all channels that belong to a parents sub categories.

Channel Categories

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

Channels

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

Get All Channels By Category Slug Route

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

ChannelController

public function index($channelCategory)
{

        //Attempt 1. Doesn't get all channels under all child categories.
        //$channels =  ChannelCategory::where('slug', $channelCategory)->first()->channels;

         Attempt 2. This works perfectly fine, but would like it to be in one query if possible
        /*if($channelCategory->id === null){
            $channels = Channel::all();
        } elseif ($channelCategory->parent_id === 0) {

            $categories = ChannelCategory::where(['parent_id' => $channelCategory->id])->pluck('id');

            $channels = Channel::whereIn('category_id', $categories)->get();

        }

        else {
            $channels = $channelCategory->channels()->get();
        }*/
         //Attempt 3 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'));
}

Maybe what I am trying to do isn't possible with a whereHas. Is it possible to do the second attempt in one query and if so how?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire