Laravel多集合合并查询:匹配租户偏好与当前用户房产
在Laravel中实现多模型关联查询:匹配租户偏好与登录用户房产
当然可以实现!在Laravel里借助模型关联和查询构造器,完全能筛选出符合条件的租户。下面一步步来帮你实现:
1. 先定义模型关联
首先要明确三个模型之间的关系:
- 一个用户(User)如果是租户,会对应一条租户偏好(TenantPreference);如果是房产所有者,会对应多条房产广告(PropertyAdvert)。
TenantPreference和PropertyAdvert都属于某个User。
在对应模型里添加关联方法:
User 模型
// 租户的偏好(一对一关联) public function tenantPreference() { return $this->hasOne(TenantPreference::class); } // 房东的房产广告(一对多关联) public function propertyAdverts() { return $this->hasMany(PropertyAdvert::class); }
TenantPreference 模型
public function user() { return $this->belongsTo(User::class); }
PropertyAdvert 模型
public function user() { return $this->belongsTo(User::class); }
2. 编写查询逻辑筛选匹配租户
假设你需要匹配的字段是位置(location)、房产类型(property_type)、租金预期范围(比如租户的rent_expectation落在房产的rent_min和rent_max之间),可以这样写:
// 获取当前登录的房产所有者用户 $currentLandlord = auth()->user(); // 筛选出所有租户,且他们的偏好与当前用户的任意房产匹配 $matchingTenants = User::where('userType', 'tenant') ->whereHas('tenantPreference', function ($query) use ($currentLandlord) { // 用子查询直接匹配租户偏好和当前用户的房产 $query->whereExists(function ($subQuery) use ($currentLandlord) { $subQuery->select(DB::raw(1)) ->from('property_adverts') // 匹配偏好和房产的对应字段 ->whereColumn('tenant_preferences.location', 'property_adverts.location') ->whereColumn('tenant_preferences.property_type', 'property_adverts.property_type') ->whereBetween('tenant_preferences.rent_expectation', [ DB::raw('property_adverts.rent_min'), DB::raw('property_adverts.rent_max') ]) // 限定是当前用户的房产 ->where('property_adverts.user_id', $currentLandlord->id); }); }) ->with('tenantPreference') // 预加载偏好,避免N+1查询问题 ->get();
3. 关键说明
whereHas:用来过滤拥有符合条件关联模型的用户,这里就是筛选出有匹配偏好的租户。whereExists:相比循环添加OR条件,子查询的方式更高效,尤其是当房产数量较多时。- 字段调整:请根据你实际的表字段名修改匹配条件,比如
userType的租户标识值、租金相关的字段名等。
如果当前用户没有任何房产,$matchingTenants会返回空集合,你可以根据业务需求添加对应的提示逻辑。
内容的提问来源于stack exchange,提问作者user9726704
相关产品推荐
相关产品推荐

