dsjk3214 2018-04-27 14:35
浏览 56
已采纳

如果不返回行,Laravel会更改关系where子句

I have the following query in my controller.

$items = Item::with(['subitems' => function($query) {
    $query->where('language_id', '=', 1);
}])->get();

This is correctly getting me all items including subitems that have a language id of 1.

There are two things I would like to do with this though

  • Firstly, I need to return all subitems that have a distinct 'ref_id' value.
  • Secondly, I would like to give preference to the language id 1 but if none exist, use any language id.

So for example, I know this code won't work, but the sort of thing I am looking for is:

$items = Item::with(['subitems' => function($query) {
    $subItems = $query->where('language_id', '=', 1)
        ->where('ref_id', 'is', 'distinct');

    if($subItems->count() <= 0) {
      $subItems = $query->where('ref_id', 'is', 'distinct');
    }
}])->get();

Is this possible or is it a bit too complicated for Query Builder? Even if one of the two requests was possible, that would be great.

  • 写回答

1条回答 默认 最新

  • doucai1901 2018-04-27 21:02
    关注

    Try this:

    $items = Item::with(['subitems' => function($query) {
        $join = Subitem::select('ref_id', DB::raw('MIN(language_id) language_id'))
            ->groupBy('ref_id');
        $sql = '(' . $join->toSql() . ') subitems_distinct';
        $query->join(DB::raw($sql), function($join) {
            $join->on('subitems.ref_id', 'subitems_distinct.ref_id')
                ->on('subitems.language_id', 'subitems_distinct.language_id');
        });
    }])->get();
    

    We can use the fact that your preferred language_id is the lowest value and select the minimum.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?