我具有以下结构:
建筑物有许多块,其中有许多单元,其中有许多'承租人'
'buildings' have many 'blocks' which have many 'units' which have many 'tenants'
我需要获取居住在建筑物中的所有租户的列表。
I need to get a list of all tenants that live in a building.
Laravel提供hasMany和hasManyThrough命令,可帮助您获取具有直接关系或通过单个中间表关联的模型的集合,但是如果您想获得两个,三个或任何级别的相关元素,该怎么办
Laravel provides hasMany and hasManyThrough commands that help you get collections of models which have direct relationship or are related through a single intermediate table but what if you want to get related elements of two, three, or any levels deep?
使用Laravel / Eloquent实现此目的的正确方法是什么?
What is the proper way to achieve this using Laravel/Eloquent?
推荐答案要查找给定建筑物中的所有租户,最简单的方法是使用 JOIN 子句。
To find all the tenants in a given building, the easiest method would be to use JOIN clauses.
我已经假设您所有的关系都是 hasMany ,而 belongsTo 则相反。
I have assumed all of your relationships are hasMany inversed by belongsTo.
$tenants = Tenant::select('tenants.*') ->join('units', 'units.id', '=', 'tenant.unit_id') ->join('blocks', 'blocks.id', '=', 'units.block_id') ->join('buildings', 'buildings.id', '=', 'blocks.building_id') ->where('buildings.id', 123) ->get();如果这是您将多次使用的内容,那么建议您创建一个查询范围在您的 Tenant 模型上。
If this is something you'll use more than once, then I'd suggest creating a query scope on your Tenant model.
class Tenant extends Eloquent { // ... public function scopeInBuilding($query, $buildingId) { return $query->select('tenants.*') ->join('units', 'units.id', '=', 'tenant.unit_id') ->join('blocks', 'blocks.id', '=', 'units.block_id') ->join('buildings', 'buildings.id', '=', 'blocks.building_id') ->where('buildings.id', $buildingId); } // ... }您可以按以下方式使用它:
And you can use it as follows:
$tenants = Tenant::inBuilding(123)->get();更多推荐
Laravel,建立深厚的关系
发布评论