检索多个表格的数据 - Laravel.

问题描述 投票:0回答:1

早上好,这是我的模型。

A 克雷蒂安 可以有很多 发布. A 发布 可谓一举多得 克雷蒂安. A 发布 属于许多 部门. A 部门 有很多 发布.

enter image description here 0..* 0..* 1..** 0.. *

我怎么才能找回这样的模型?

                         John DOE
        ---------------------------------------
        |**Postes**       | **Departements**  |
        ---------------------------------------
        |Pianist          | Musical Group     |
        ---------------------------------------
        | Secretary Curch | council           |
        ---------------------------------------
        |Wedding Planer   | Organizatin Comite|
sql laravel-5 eloquent many-to-many relationship
1个回答
0
投票

当以属性形式访问Eloquent关系时,关系数据是 "懒加载 "的。这意味着关系数据在你第一次访问属性之前不会被实际加载。但是,Eloquent可以在你查询父模型时 "急切加载 "关系。急切加载减轻了 N + 1 查询的问题。为了说明N + 1查询问题,考虑一个与Poste相关的Chretien模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Poste extends Model
{
    /**
     * Get the chretien that wrote the poste.
     */
    public function chretien()
    {
        return $this->belongsTo('App\Chretien');
    }
}

现在,让我们检索所有的chretiens和他们的poste。

$chretiens = App\Chretien::with('postes')->get();

foreach ($chretiens as $chretien) {
    echo $chretien->postes->name;
}

对于这个操作,只有两个查询会被执行。

select * from chretiens 

select * from postes where id in (1, 2, 3, 4, 5, ...)

嵌套的急切加载

要急切地加载嵌套关系,你可以使用 "点 "语法。例如,让我们在一个Eloquent语句中急切地加载所有的poste和所有的departament。

$chretiens = App\Chretien::with('postes.departaments')->get();
© www.soinside.com 2019 - 2024. All rights reserved.