1、with('relation'),只预加载relation这个关联,如下面
public function relation() { return $this->hasOne(Relation::class); }
2、with(['relation', 'relation.relation1']),预加载relation以及,和relation关联的relation1
这种场景是Relation类中还定义了一个关联relation1
class Relation { public function relation1() { return $this->hasOne(Relation1::class); } }
这样一来,一个with就把当前模型的关联relation以及relation的下级关联relation1查询出来了,
这对hasMany这种关联特别有好处,如果hasMany这种不使用预加载的话,每访问一次就会查询一次,而不是一次把多条关联数据查询出来。
测试:
数据库:两个表,一个是relation表,只有id字段;另一个是relation1表,除了id之外,还有关联relation表的relation_id。
控制器文件:
<?php namespace app estcontroller; use app estmodelRelation; use thinkController; class Test extends Controller { public function test(Relation $relationModel) { /** @var app estmodelRelation[] $relations */ $relations = $relationModel->select(); foreach ($relations as $relation) { /** @var app estmodelRelation $relation */ foreach ($relation->relation1 as $relation1) { /** @var app estmodelRelation1 $relation1 */ echo $relation1->id . PHP_EOL; } } } public function test1(Relation $relationModel) { /** @var app estmodelRelation[] $relations */ $relations = $relationModel->with('relation1')->select(); foreach ($relations as $relation) { /** @var app estmodelRelation $relation */ foreach ($relation->relation1 as $relation1) { /** @var app estmodelRelation1 $relation1 */ echo $relation1->id . PHP_EOL; } } } }
模型文件
Relation.php
<?php namespace app estmodel; /** * Class Relation * @package app estmodel * * @property Relation1[] relation1 */ class Relation extends BaseModel { public function relation1() { return $this->hasMany(Relation1::class); } }
Relation1.php
<?php namespace app estmodel; /** * Class Relation1 * @package app estmodel * * @property integer id */ class Relation1 extends BaseModel { }
结果:
不使用with预加载,每次循环都进行sql查询
使用预加载的时候,关联的数据只进行了一次查询: