尝试获取无效的关键记录,其中每个连接的记录均处于非活动状态(Laravel elequent查询)

时间:2019-07-09 09:12:47

标签: laravel eloquent relationship laravel-query-builder

我有2张桌子

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

我正在尝试停用所有sub_categories的所有类别( means are soft-deleted )

让我解释更多

我有sub_categories个数据

    [
    {
        "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"
    }
]

我只想要category_id-> 2(其中所有sub_categories都是softedeleted

听力的类别模型代码

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

3 个答案:

答案 0 :(得分:0)

您首先必须定义CategorysSub_categories-https://laravel.com/docs/5.8/eloquent-relationships之间的关系。 然后使用查询获取您想要的https://laravel.com/docs/5.8/queries

答案 1 :(得分:0)

获取具有子类别的类别ID:

$categoryIdsWithSubCategories = SubCategory::get()->pluck('category_id')->toArray();

获取没有子类别的类别:

$categoriesWithoutSubCategories = Category::whereNotIn('id', $categoryIdsWithSubCategories)->get();

答案 2 :(得分:0)

$categories = Categories::doesntHave('subCategory')->get();