如何返回雄辩的关系,但只选择非空的列?

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

所以我有一个关系,客户端附加到一个单引号和客户端有一组测量(但我称之为测量,抱歉有点混乱,但它的工作原理)。因此,如果我将$quote绑定到我的路线并做return $quote->client-measurement;我得到以下内容:

{
    "id": 11,
    "client_id": 5,
    "eaves": "101.15",
    "ridges": "50.57",
    "hips": null,
    "valleys": null,
    "rakes": "95.08",
    "drip_edge": null,
    "flashing": "1.01",
    "step_flashing": null,
    "quote_id": null,
    "item_id": null,
    "created_at": "2019-01-08 17:14:43",
    "updated_at": "2019-01-08 17:14:43",
    "total_roof_area": "20.87",
    "total_steep_slope_area": "12.61",
    "total_low_slope_area": "8.27",
    "length": null,
    "width": null,
    "parapet_walls": null,
    "roof_penetrations": null,
    "total_low_slope_area_without_penetrations": null,
    "penetrations_perimeter": null,
    "roof_length": null
}

有没有办法我只能选择那些非空的列?我知道我可以存储它然后遍历它并恢复值但我觉得这是非常低效的。有任何想法吗?

laravel select eloquent isnull
2个回答
1
投票

作为@travis-britz答案的补充,您还可以执行以下操作:

return array_filter($quote->client-measurement->toArray());

你可以找到有关array_filter here的文档。


1
投票

假设client-measurement是一个Eloquent模型,你可以使用filter()

return collect($quote->client_measurement)->filter();

filter方法使用给定的回调过滤集合,仅保留那些通过给定真值测试的项目。

如果未提供回调,则将删除与false等效的集合的所有条目。

https://laravel.com/docs/5.8/collections#method-filter

© www.soinside.com 2019 - 2024. All rights reserved.