【问题标题】:Laravel: Relation empty after using `whereHas` and `with`?Laravel:使用`whereHas`和`with`后关系为空?
【发布时间】:2018-10-26 22:06:15
【问题描述】:

我有这个问题:

 $user =  \App\User::where('id','=',191)
            ->whereHas('addresses', function($q){
              $q->getByDistance(52.5293878, 13.3416309, 5);
            })
            ->with(['addresses' => function($q){
              $q->getByDistance(52.5293878, 13.3416309, 5);
            }])
            ->get();

dd($user);

这会选择 ID 为 191 的用户,前提是他的地址在范围内,然后他也急切地加载该地址。

这是addresses 类中的scopeGetByDistance 函数

public static function scopeGetByDistance($query,$lat, $lng, $max_distance)
{
  return $query->selectRaw('lat, lng, ( 3959 * acos( cos( radians( '.$lat.') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) ) AS distance')
               ->having('distance', '<', $max_distance )
               ->orderBy( 'distance', 'ASC' );
}

我选择了id 191 的用户,因为我知道他的地址与坐标的距离约为 2。

这将输出一个用户,但关系为空。 whereHas 不应该确保关系不为空吗?我也确定他必须有一个范围内的地址。这就是关系的样子:

【问题讨论】:

  • 请添加scopeGetByDistance()的代码。当您只使用-&gt;with('addresses') 时,这种关系是否有效?
  • @JonasStaudenmeir 我改进了问题并添加了scopeGetByDistance() 函数。是的,如果我只使用 with('addresses') 一切正常。

标签: laravel-5 eager-loading laravel-query-builder


【解决方案1】:

我必须像这样将引用键添加到selectRaw

return $query->selectRaw('user_id, lat, lng, ( 3959 * acos( cos

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2022-01-27
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2021-07-27
    • 1970-01-01
    • 2014-01-11
    相关资源
    最近更新 更多