Laravel 中的关系检索差异
Relations retrieval difference in Laravel
有什么区别
$this->translations;
和
$this->translations()->get();
其中 translations 是当前模型的关系。我以为两者做同样的事情。
它们基本上是一样的。
但是:
$this->translations()->get();
每次调用都会查询数据库。
$this->translations;
会第一次执行数据库查询,并将结果存储在内存中供以后使用。
$this->translations;
将 return 所有翻译到相关模型,
而 $this->translations()
将为您提供查询构建器实例,您可以在其中将约束添加到相关模型中,例如
$this->translations()->where(['locale' , 'en'])->orderBy('sort')->get();
$this->translations;
和
$this->translations()->get();
其中 translations 是当前模型的关系。我以为两者做同样的事情。
它们基本上是一样的。
但是:
$this->translations()->get();
每次调用都会查询数据库。$this->translations;
会第一次执行数据库查询,并将结果存储在内存中供以后使用。
$this->translations;
将 return 所有翻译到相关模型,
而 $this->translations()
将为您提供查询构建器实例,您可以在其中将约束添加到相关模型中,例如
$this->translations()->where(['locale' , 'en'])->orderBy('sort')->get();