Laravel,建立深厚的关系 [英] Laravel, getting deep relationships

查看:99
本文介绍了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,建立深厚的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆