【问题标题】:Referencing foreign key data in WHERE clause in Eloquent在 Eloquent 的 WHERE 子句中引用外键数据
【发布时间】:2016-07-30 04:24:48
【问题描述】:

我有两张表 Songs (belongsTo App\Host) 和 Hosts (hasMany App\Song)。我的 Songs 表有一个 attempts 列,而我的 Host 表有一个 skip_threshold。我想查询出所有未达到其相关主机跳过阈值的歌曲。

我该怎么做?

我尝试过这样的事情:

return $songs = Song::whereIn('host_id', $available_hosts)
                       ->where('attempts', '<', $songs->host->skip_threshold)->get();

我尝试使用 Eloquent 关系查询,但从测试中我发现这不起作用。我想尝试使用 Eloquent 来执行此操作,这样我就可以利用在刀片模板中预先加载相关数据的优势。

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    你可以试试

    $songs = Song::whereHas('host', function($query) {
        $query->where('skip_threshold', '>', DB::raw('songs.attempts'));
    })->get();
    

    【讨论】:

    • 这可以按需要工作,但删除了 WhereIn 子句,如何将其添加到查询中?我只想允许查询某些主机密钥
    • 简单地说,就像你之前描述的那样。 @David 为你做的。
    【解决方案2】:

    如果我理解您要查找的内容,您可以将 where 子句链接在一起,如下所示:

    $songs = Song::whereHas('host', function($query) {
        $query->where('skip_threshold', '>', DB::raw('songs.attempts'));
    })->whereIn('host_id', $available_hosts)->get();
    

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      相关资源
      最近更新 更多