在我的应用程序中,一个地址可以有很多地方,现在我想检索所有地址,并将位置数附加到每个地址,我该如何使用 Eloquent 来做到这一点?
$address= Address::with('places')->get();
Run Code Online (Sandbox Code Playgroud)
提前致谢
使用雄辩的withCount():
$address = Address::withCount('places')->get();
Run Code Online (Sandbox Code Playgroud)
它将返回每个模型与字段相关的行数
$address->places_count
Run Code Online (Sandbox Code Playgroud)
官方文档可以在这里withCount找到