【问题标题】:Laravel multiple whereHas criteria for relationshipLaravel 多个 whereHas 关系标准
【发布时间】:2014-11-29 10:42:20
【问题描述】:

我有两张表 - 联系人和访问:

联系人表

id    | name          
----- | -------
1     | Joe
2     | Sally

访问表

id    | contact_id | pathname  | referrer                
----- | -------    | -------   | -------
1     | 1          | about     | google
2     | 1          | pricing   | null
3     | 1          | signup    | null
4     | 2          | about     | null
5     | 2          | signup    | null

使用 eloquent,我想检索具有 路径名 = 'signup' 和 referrer = 'google 的所有 联系人 '。

到目前为止我得到的是:

Contact::whereHas('visits', function($query) {
    $query->where('pathname','=','signup');
})
->orWhereHas('visits', function($query) {
    $query->where('referrer','=','google');
})
->get();

正确检索访问过定价或注册页面的所有联系人。

但是,此示例也将检索 Sally(来自上面的示例表),因为她访问了注册,但未被 google 推荐。我需要一种方法来只检索 Joe,他既被 google 推荐,又被访问过定价。

有什么想法吗?提前致谢!

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    你可以使用:

    Contact::whereHas('visits', function($query) {
        $query->where('pathname','=','signup');
    })
    ->whereHas('visits', function($query) {
        $query->where('referrer','=','google');
    })
    ->get();
    

    【讨论】:

    • 这正是我想要的。谢谢马辛!
    【解决方案2】:

    上述代码的改进版:

    Contact::whereHas('visits', function($query) {
        $query->where('pathname','signup')->where('referrer','google');
    })->get();
    

    几个值得注意的点:

    1. 您可以在闭包中链接where() 子句。
    2. where 子句的默认运算符是=,因此您可以省略它。
    3. 在访问多个相关模型时,使用多个 whereHas() 子句。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2014-01-11
      • 2016-09-11
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 2016-09-05
      • 2021-05-25
      相关资源
      最近更新 更多