[英]question about laravel relationships and performance
i hope you are having a good time.我希望你玩得开心。 i am learning laravel and the inscuctor talked about when you load relationships in laravel, like so我正在学习 laravel 和 inscuctor 谈到当你在 laravel 中加载关系时,像这样
public function timeline()
{
$ids = $this->follows()->pluck('id');
$ids->push($this->id);
return Tweet::whereIn('user_id', $ids)->latest()->get();
}
and i have a follows relationship in my model, and he talked about this line我在我的 model 中有关注关系,他谈到了这一行
$ids = $this->follows()->pluck('id');
being better for performance than this line性能比这条线更好
$ids = $this->follows->pluck('id');
my question is, how does laravel pluck the ids in the first case, and how it queries the database i hope im making sense, thanks for your time, and answer.我的问题是,laravel 在第一种情况下如何提取 ID,以及它如何查询数据库我希望我能理解,感谢您的时间和回答。
the following one executes a select query on database以下是对数据库执行 select 查询
$this->follows()->pluck('id');
the follows()
returns a query builder (which is a not yet executed sql statement) and then on the result select the id column and returns a collection of id
s follows()
返回一个查询生成器(这是一个尚未执行的 sql 语句),然后在结果 select 上返回 id 列并返回id
的集合
you can see the query by dumping the query builder by $this->follows()->dd()
您可以通过$this->follows()->dd()
转储查询构建器来查看查询
Whereas in the second option而在第二个选项中
$this->follows->pluck('id')
up until $this->follows
laravel executes a query and returns all the records as a collection instance, You will be able to see all the attributes on each of the records.直到$this->follows
laravel 执行查询并将所有记录作为集合实例返回,您将能够看到每条记录上的所有属性。 And then ->pluck('id')
is getting executed on the laravel collection class, which will do an operation I assume similar to the array_column
function does and returns only the id
column.然后->pluck('id')
在 laravel 集合 class 上执行,我认为这将执行类似于array_column
function 所做的操作并仅返回id
列。
as you can easily see in the second operation the whole data set was retrieved first from the DB and then selected the required attribute/column (2 distinct and heavy operations).正如您在第二个操作中可以轻松看到的那样,首先从数据库中检索整个数据集,然后选择所需的属性/列(2 个不同且繁重的操作)。 Where as in the first option we directly told eloquent to select only the required column, which is only one lighter operation compared to the second option.在第一个选项中,我们直接告诉 eloquent 到 select 只有所需的列,与第二个选项相比,这只是一个更轻的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.