gpt4 book ai didi

php - Laravel - 渴望加载多对多,只获取一条记录(不是集合)

转载 作者:可可西里 更新时间:2023-10-31 23:38:35 24 4
gpt4 key购买 nike

我的帖子有图片(多对多,因为图片也可以有其他关系)。在我的数据透视表中,我有一个名为“特色”的 bool 字段,它指定该帖子的主图像。我想在帖子索引页面中显示与当前用户关联的所有帖子。我只想从数据库中获取一张图片,那应该是特色图片。目前我只能将精选图片作为一个集合。这样做的原因是,如果用户有很多帖子,我不想继续检索他们所有帖子 (N+1) 的特色图片,而是使用预加载仅通过 2 个查询获取特色图片。

\\Post Model
public function images() {
return $this->belongsToMany(Image::class);
}

public function image(){
return $this->images()->where('featured', '=', true)->first();
}

public function featured_image(){
return $this->images()->where('featured', '=', true);
}


\\Controller

$user = Auth::user();

$posts = $user->posts()->with('image')->get();

// throws error
//Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()


// if I do this
$posts = $user->posts()->with('featured_image')->get();

// I get all the user's posts, I get the featured image but as a collection even if I only have one record there

我该怎么做?

最佳答案

我认为这可能是您想要的解决方案:

\\Post Model

public function images() {
return $this->belongsToMany(Image::class);
}

public function getFeaturedImageAttribute() {
return $this->images->where('featured', true)->first();
}


\\Controller

$user = Auth::user();

$posts = $user->posts()->with('images')->get();

在生成的帖子集合中,每个帖子都有一个“featured_image”属性,可以像这样访问:

foreach ( $posts as $post )
{
$featured_image = $post->featured_image;

// do something with the image...
}

重要提示:因为访问器方法使用“$this->images”而不是“$this->images()”,它将使用预先加载的“images”集合的 where() 和 first() 方法而不是运行查询生成器。这导致大量 PHP 处理但没有新查询。

关于php - Laravel - 渴望加载多对多,只获取一条记录(不是集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33857840/

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