Ad

Trying To Get Foraign Key Records Where Every Connected Records Are Deactive ( Laravel Elequent Query )

I have 2 tables

Category's ( id, name )
Sub_categories ( id, key, value, category_id )

I'm trying to get all Category's whose all sub_categories are deactivated ( means are soft-deleted )

let me explain more

i have sub_categories data like this

    [
    {
        "id": 1,
        "category_id": 1,
        "key": "sub 1",
        "value": "sub_1",
        "deleted_at": null
    },
    {
        "id": 2,
        "category_id": 1,
        "key": "sub 2",
        "value": "1",
        "deleted_at": null
    },
    {
        "id": 4,
        "category_id": 1,
        "key": "sub 3",
        "value": "1",
        "deleted_at": "2019-07-09 06:06:01"
    },
    {
        "id": 5,
        "category_id": 2,
        "key": "sub 1",
        "value": "33",
        "deleted_at": "2019-07-09 06:06:01"
    },
    {
        "id": 6,
        "category_id": 2,
        "key": "sub 2",
        "value": "33",
        "deleted_at": "2019-07-09 06:06:01"
    }
]

i want only category_id -> 2 ( where all sub_categories are softedeleted )

hear's category model code

    public function subCategory() {
         $this->makeVisible('deleted_at');
         return $this->hasMany('App\SubCategory','category_id','id');
    }
Ad

Answer

$categories = Categories::doesntHave('subCategory')->get();
Ad
source: stackoverflow.com
Ad