gpt4 book ai didi

php - 像 belongsTo 这样的 Laravel 关系方法是否总是查询数据库?

转载 作者:可可西里 更新时间:2023-11-01 00:56:53 25 4
gpt4 key购买 nike

我只是想更好地了解 Laravel 的 Eloquent/Model 是如何处理关系的。

假设我定义了一个关系,其中每个 Post 都有一个 Author 并且 Post 类有一个方法来获取与之关联的作者对象:

public function author() {
return $this->belongsTo( 'App\User', 'author_id' );
}

现在调用帖子的 author() 方法将根据帖子的 author_id 字段返回作者。我的问题是:每次使用该方法时,Laravel 是否都会进行查询?以下代码是否会向数据库请求两次数据?

<a href="{{ route('user',$post->author->slug) }}">{{ $post->author->name }}</a>

最佳答案

这个问题,有例子,有完整的记录right here .

其中提到:

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property.

你可以

When querying, you may specify which relationships should be eager loaded using the with method:


因此,当您调用 $post->author 时,您只进行了一次查询,并重复使用了之前查询中的相同数据。

但是,如果您也这样做,比方说,多个帖子并遍历它们以询问他们的作者,每个请求都会是一个新的查询。除非模型有 protected $with = ['author'] 属性,或者查询中包含 with 以急切地加载它。

$post = App\Post::with('author')->find(2)->get();

所有的数据都会被预先加载,并且只有一个执行的查询。

关于php - 像 belongsTo 这样的 Laravel 关系方法是否总是查询数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39506764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com