Laravel 如何返回雄辩的关系,但只选择不为null的列?

Laravel 如何返回雄辩的关系,但只选择不为null的列?,laravel,select,eloquent,isnull,Laravel,Select,Eloquent,Isnull,因此,我有这样一种关系:一个客户被附加到一个报价单上,而一个客户有一组度量值(但我称之为度量值,很抱歉有点混淆,但它是有效的)。因此,如果我将$quote绑定到我的路由,并执行返回$quote->客户机度量我得到以下信息: { "id": 11, "client_id": 5, "eaves": "101.15", "ridges": "50.57", "hips": null, "valleys": null, "rakes": "95.

因此,我有这样一种关系:一个客户被附加到一个报价单上,而一个客户有一组度量值(但我称之为度量值,很抱歉有点混淆,但它是有效的)。因此,如果我将
$quote
绑定到我的路由,并执行
返回$quote->客户机度量我得到以下信息:

{
    "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
}
return array_filter($quote->client-measurement->toArray());

有没有办法只选择那些不为空的列?我知道我可以把它全部存储起来,然后在其中循环并恢复值,但我觉得这样做效率太低了。有什么想法吗?

假设
客户衡量
是一个有说服力的模型,您可以使用
filter()

return-collect($quote->client_-measurement)->filter();
filter
方法使用给定回调过滤集合, 只保留通过给定真理测试的项目

如果未提供回调,则返回 将删除相当于
false


除了@travis britz answer,您还可以执行以下操作:

{
    "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
}
return array_filter($quote->client-measurement->toArray());

你可以找到关于
array\u filter

的文档,你是说作为API返回?如果是这样的话,您正在寻找一个从未了解过过滤器的plus,请尽快查看它。这看起来肯定会有用的。非常感谢你。