【问题标题】:Use DISTINCT on joined columns with Laravel Query builder使用 Laravel 查询构建器在连接列上使用 DISTINCT
【发布时间】:2014-05-29 21:57:57
【问题描述】:

我有两个表产品和工件,它们彼此之间存在一对多关系。

现在我想查询一些与产品数据结合的工件。 这很好用:

$artifacts = Artifact::with('product')->get();

但是现在我想使用 DISTINCT 命令并从两个表中选择必要的字段来考虑使用 DISTINCT。遗憾的是,所有连接的列都失败了。

$artifacts = Artifact::with('product')->select('product.organization, revision')->distinct()->get();

【问题讨论】:

  • with('product') 不加入任何内容,但会使用 WHERE IN 语句对 products 表进行第二次查询,因此请描述您想要使用 distinct 的确切内容,并且是与许多产品的关系工件还是其他方式?
  • 我想在基于 $artifacts 呈现的视图中消除重复的工件。一种产品有很多工件。
  • 这个查询应该有机会返回重复项,所以你得到了那些,或者你得到了错误/异常,因为没有 product.organization 字段?如果有重复,请粘贴查询(例如 DB::getQueryLog() )

标签: mysql sql laravel laravel-4


【解决方案1】:
return DB::table('artifacts')
        ->join('products','products.id', '=', 'artifacts.product_id')
        ->distinct()
        ->get();

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 2015-03-02
    • 2018-07-03
    • 2020-08-29
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2016-11-25
    • 2018-07-20
    相关资源
    最近更新 更多