Laravel Eloquent with()选择特定的列不会返回结果

问题描述 投票:1回答:2

说我有2个模型,类别和POI,其中1个类别可以有很多POI。

$categoryDetails = Category::with([
    'pois' => function ($query) {
        $query->where('is_poi_enabled', true);
    },
])->findOrFail($id);

上面的查询返回特定类别及其POI的结果。

但是,使用以下查询:

$query->select('id', 'name')->where('is_poi_enabled', true);

POI在集合中变为空。

知道为什么会这样吗?在向Eloquent ORM添加select子句时?

laravel
2个回答
1
投票

进行选择时,需要提取关系本地或主键。例如,POIs表包含category_id,则需要选择它试试这个:

$categoryDetails = Category::with([
    'pois' => function ($query) {
        $query->select(['id', 'category_id', 'is_poi_enabled'])
       ->where('is_poi_enabled', true);
    },
])->findOrFail($id);

祝你好运!


0
投票

您可以尝试此操作

$categoryDetails = Category::with([
    'pois' => function ($query) {
        $query->select(['id','is_poi_enabled'])
       ->where('is_poi_enabled', true);
    },
])->findOrFail($id);
© www.soinside.com 2019 - 2024. All rights reserved.