试图获取每个连接记录都处于非活动状态的外键记录(Laravel 雄辩查询)
Posted
技术标签:
【中文标题】试图获取每个连接记录都处于非活动状态的外键记录(Laravel 雄辩查询)【英文标题】:Trying to get foraign key records where every connected records are deactive ( Laravel elequent query ) 【发布时间】:2019-11-18 19:23:57 【问题描述】:我有两张桌子
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');
【问题讨论】:
你能把你的型号代码分类 【参考方案1】:$categories = Categories::doesntHave('subCategory')->get();
【讨论】:
当一个或多个子类别被停用时,此代码返回....我想在所有子类别都被停用时...【参考方案2】:您首先必须定义Categorys
和Sub_categories
- https://laravel.com/docs/5.8/eloquent-relationships 之间的关系。
然后使用查询得到你想要的https://laravel.com/docs/5.8/queries
【讨论】:
【参考方案3】:获取具有子类别的类别ID:
$categoryIdsWithSubCategories = SubCategory::get()->pluck('category_id')->toArray();
获取没有子类别的类别:
$categoriesWithoutSubCategories = Category::whereNotIn('id', $categoryIdsWithSubCategories)->get();
【讨论】:
以上是关于试图获取每个连接记录都处于非活动状态的外键记录(Laravel 雄辩查询)的主要内容,如果未能解决你的问题,请参考以下文章
如何在应用程序处于非活动状态时获取推送通知ios swift3