使用 Laravel 查询构建器在连接列上使用 DISTINCT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23085543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use DISTINCT on joined columns with Laravel Query builder
提问by Hedge
I've got two tables products and artifacts who are in a one-to-many-relationship to each other.
我有两个表产品和工件,它们之间是一对多的关系。
Now I'd like to query a few artifacts joined with the products-data. This works very good like this:
现在我想查询一些与产品数据相连的工件。这非常有效,如下所示:
$artifacts = Artifact::with('product')->get();
However now I'd like to use the DISTINCT command and select the necessary fields to consider with DISTINCT from both tables. Sadly all joined columns fail.
但是现在我想使用 DISTINCT 命令并从两个表中选择要考虑 DISTINCT 的必要字段。遗憾的是,所有连接的列都失败了。
$artifacts = Artifact::with('product')->select('product.organization, revision')->distinct()->get();
回答by Dammy
return DB::table('artifacts')
->join('products','products.id', '=', 'artifacts.product_id')
->distinct()
->get();