Laravel,建立深厚的关系

编程入门 行业动态 更新时间:2024-10-24 04:47:30
本文介绍了Laravel,建立深厚的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我具有以下结构:

建筑物有许多块,其中有许多单元,其中有许多'承租人'

'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,建立深厚的关系

本文发布于:2023-10-30 23:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544374.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:深厚   关系   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!