[英]How to check if a Laravel eloquest relation is eagerLoaded on the retrieved event of a model?
我會盡量簡化問題。
我想禁用在retrieved
到的事件中發生的資源特征的關系加載。
有一個我們將命名為Post
的 model,它使用名為HasComments
的特征。
class Post extends Model
{
use HasComments;
...
}
該特征偵聽 model 上retrieved
到的事件並加載comments
關系。
trait HasComment
{
public static function bootHasComment(): void
{
self::retrieved(function ($model) {
$model->load('comments');
});
}
public function comments(): BelongsTo
{
return $this->belongsTo(Comment::class);
}
}
我希望能夠檢查comments
關系是否已預先加載並且不再加載該關系。
我試圖檢查關系是否已加載但失敗了。
前任:
self::retrieved(function ($model) {
if (!isset($model->relations['comments'])) {
dd('still loads!');
$model->load('comments');
}
});
或者
self::retrieved(function ($model) {
if (!$model->relationLoaded('comments')) {
dd('still loads!');
$model->load('comments');
}
});
我也在想也許有一種方法可以在構造查詢時禁用此行為但再次失敗。
前任:
trait HasComment
{
public bool $load = true;
public static function bootHasComment(): void
{
self::retrieved(function ($model) {
if (!$this->load) {
dd('still loads!');
$model->load('comments');
}
});
}
public function comments(): BelongsTo
{
return $this->belongsTo(Comment::class);
}
public function disableRetrievedLoad()
{
$this->load = false;
}
}
有人遇到過類似的事情可以給我一些幫助嗎?
有一個名為relationLoaded
的方法返回 boolean。看起來很適合您的需求。
或者,如果您想要加載尚未加載的關系,則可以loadMissing
。
$post = Post::first();
$post->relationLoaded('comments'); // false
$post->loadMissing('comments'); // makes the queries to load the relationship
$post->relationLoaded('comments'); // true
$post->loadMissing('comments'); // does nothing. comments is already loaded
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.