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

标签 php laravel eloquent many-to-many

我的帖子有图片(多对多,因为图片也可以有其他关系)。在我的数据透视表中,我有一个名为“特色”的 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/

相关文章:

phpunit 测试套件的独立性

php - 向 Eloquent 资源添加过滤器以有条件地附加关系

php - Laravel 查询构建器中留下的 SQL 连接

php - 在表单中嵌套模型关系 - Laravel

php - Laravel Eloquent : Inverse of Many To Many (Polymorphic)

php - Laravel Eloquent 计算

javascript - 插入父帖子vue js的子评论

php - 如何在添加行时获取表列的值

php - 组织的简单网站

laravel - 通过 Laravel Sail 安装并在端口上可用 Meil​​isearch 不会添加模型索引; date.ms 文件似乎丢失