【问题标题】:Laravel get users by state using city idLaravel 使用城市 id 按州获取用户
【发布时间】:2021-06-30 14:55:05
【问题描述】:

我有users 表,其中有city_idcities 表中的每个城市都有state_id。如何让任何州的用户使用city_id

这是我的代码:

$users = User::role('company')
            ->when((int) $state, function ($query, $state) {
                // here query
            })
            ->when((int) $city, function ($query, $city) {
                return $query->where('city_id', $city);
            })
            ->get();

我试过了:

$users = User::role('company')
            ->when((int) $state, function ($query, $state) {
                $cities = City::where('state_id', $state)
                            ->pluck('id')
                            ->toArray();
                return $query->whereIn('city_id', $cities);
            })
            ->when((int) $city, function ($query, $city) {
                return $query->where('city_id', $city);
            })
            ->get();

这是可行的,但是如何在不使用City 模型进行新查询的情况下正确执行此查询?

【问题讨论】:

    标签: laravel eloquent relationship laravel-8


    【解决方案1】:

    你建立了用户和城市之间的关系吗?它应该是这样的:

     public function city()
        {
            return $this->belongsTo(City::class, 'city_id');
        }
    

    您可以使用该关系让用户where has 属于该州的城市:

    $users = User::role('company')
                ->when((int) $state, function ($query)use ($state) {
                    return $query->whereHas('city',function ($query)use ($state){
                        $query->where('state_id',$state);
                    });
                })
                ->when((int) $city, function ($query)use($city) {
                    return $query->where('city_id', $city);
                })
                ->get();
    

    【讨论】:

    • 嗨@Andreas Hunter,感谢您的编辑,不管有没有返回,内联函数都可以正常工作,但是像您的编辑一样使用返回更清晰。
    【解决方案2】:

    你可以使用 Laravel HasManyThough

    假设你有一个州,每个州有很多城市,每个城市有很多用户

    那么在状态模型中,可以添加这个函数

    public function users()
    {
        return $this->hasManyThrough(User::class, City::class);
    }
    

    这个函数将返回给定状态的所有用户

    示例:

    $state = State::first();
    $users = $state->users;
    

    更多信息请阅读docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2017-09-02
      • 2022-09-26
      • 2013-02-08
      • 1970-01-01
      • 2014-09-08
      • 2011-10-31
      相关资源
      最近更新 更多