检索多个表上的数据-laravel

vi4fp9gy  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(277)

早上好,这是我的模型:
一个基督徒可以有很多职位。一个职位可以属于许多人。邮局属于许多部门。一个部门有许多职位。
克雷蒂安

sf6xfgos

sf6xfgos1#

-部门

0..* 0..* 1..**0.. *
我怎样才能找回这样的模型?

John DOE
        ---------------------------------------
        |**Postes**     |**Departements**|
        ---------------------------------------
        |Pianist          | Musical Group     |
        ---------------------------------------
        | Secretary Curch | council           |
        ---------------------------------------
        |Wedding Planer   | Organizatin Comite|
sxpgvts3

sxpgvts32#

当作为属性访问有说服力的关系时,关系数据是“延迟加载的”。这意味着在您首次访问属性之前,关系数据不会被实际加载。但是,雄辩者可以在查询父模型时“急切地加载”关系。急于加载减轻了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 = 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, ...)

嵌套急加载
要加载嵌套关系,可以使用“点”语法。例如,让我们在一个雄辩的语句中加载所有的poste和department:

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

相关问题