【问题标题】:Retrieve an Eloquent Model Based on It's Many to Many Relationships基于多对多关系检索 Eloquent 模型
【发布时间】:2020-12-15 01:37:49
【问题描述】:

假设我有一个博客模型、帖子模型和一个照片模型。

  • 一个博客可以有很多帖子。
  • 帖子属于博客。
  • 一个帖子属于许多照片。
  • 一张照片属于许多帖子。
posts Table
id | blog_id | text

photos Table
id | text

photo_post Table
post_id | photo_id

我要做的是在指定的博客上找到一个特定的帖子,上面有两张特定的照片。

我正在努力用 Eloquent 检索这条 Post 记录。

    $post = Post::where('blog_id', $blog->id)
        ->whereHas('photos', function($q) {
            $q->where('photo_id', 180)->where('photo_id', 181);
        })->firstOrFail();

每个博客只有一个实例,其中两张照片在一篇文章中使用。

有什么建议吗?

【问题讨论】:

  • 那么您遇到的查询问题是什么
  • 它不工作。
  • 我已经在数据库中验证了记录是用来提取这个的。
  • 当你使用$q->where('photo_id', 180)->where('photo_id', 181); 时,它就像WHERE photo_id = 180 AND photo_id = 181,所以它自然不会起作用。已使用whereIn 发布了答案

标签: php laravel eloquent


【解决方案1】:

您可以使用whereIn

$post = Post::where('blog_id', $blog->id)
    ->whereHas('photos', function($q) {
        $q->whereIn('photo_id', [180, 181]);
    })
    ->firstOrFail();

【讨论】:

  • 这行得通。当它允许我时,我会在几分钟内接受它。 :P 谢谢
  • 你能在那里做第一个或创建吗?
  • @ahackney 不,不能。 firstOrCreate 具有 firstOrCreate(array $attributes, array $values) 的签名,其中 $attributes 包含 $key => $value 对,对数据库中的现有记录进行搜索。如果未找到记录,则创建带有 $values 的新记录。在您的情况下,如果您想检查是否存在与给定 id 的两张照片相关联的帖子,如果不创建新的帖子记录 - 您可以先写而不是 firstOrFail。然后如果 $post(由 first() 返回)为空,则创建一条新记录
猜你喜欢
  • 2019-08-17
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 2010-10-17
  • 2018-11-26
相关资源
最近更新 更多