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

Cri*_*ian 6 php many-to-many laravel eloquent

我的帖子有图片(多对多,因为图片也可以有其他关系)。在我的数据透视表中,我有一个名为“featured”的布尔字段,它指定了该帖子的主图像。我想在帖子索引页面中显示与当前用户关联的所有帖子。我只想从数据库中获取一张图片,那应该是特色图片。目前我只能将精选图片作为集合。这样做的原因是,如果用户有很多帖子,我不想继续检索他们所有帖子的特色图片 (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
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Tri*_*rip 2

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

\\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();
Run Code Online (Sandbox Code Playgroud)

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

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

    // do something with the image...
}
Run Code Online (Sandbox Code Playgroud)

重要提示:由于访问器方法使用 '$this->images' 而不是 '$this->images()',因此它将使用急切加载的 'images' 集合的 where() 和 first() 方法而不是查询生成器来运行。这会导致相当大的 PHP 处理量,但没有新的查询。