具有多个关系的 Laravel 数据库查询



我想从数据库中加载特定年龄用户的帖子。用户可以保存最小值(用户>配置文件>min_age(和 其个人资料中的最长年龄(用户>个人资料->max_age(。

我收到的登录用户的年龄,如下所示:

Auth::user()->birthday->diff(Carbon::now())->format('%y');

但是,每次我需要创建帖子的用户的年龄时。我无法在同一个查询中获取年龄...我很困惑

这是我当前的查询,但没有年龄:

Post::where('type', 7)->whereIn('gender', [0,1])->where('user_id', '!=' , Auth::user()->id)
->whereNotExists(function ($query) {
$query->select(DB::raw(1))
->from('users_finder')
->whereColumn('users_finder.post_id', 'posts.id')
->where('users_finder.user_id', auth()->id());
})->first();

后.php

public function user() {
return $this->belongsTo('AppUser', 'user_id');
}

用户.php

public function posts()
{
return $this->hasMany('AppPost');
}
public function profile()
{
return $this->hasOne('AppProfile');
}

简介.php

public function users()
{
return $this->belongsTo('AppUser');
}

这是否适用于何处或我必须为此使用联接? 如何加载相应的帖子?

您可以将此约束添加到帖子查询中:

// TODO: set these from current user
$minAge = 25;
$maxAge = 28;
$posts = Post::query()
->where('type', 7)
->where('user_id', '!=' , auth()->id())
->whereIn('gender', [0,1])
->whereNotExists(function ($query) {
$query->select(DB::raw(1))
->from('users_finder')
->whereColumn('users_finder.post_id', 'posts.id')
->where('users_finder.user_id', auth()->id());
})
->whereHas('user', function ($query) use ($minAge, $maxAge) {
$query->whereRaw('timestampdiff(YEAR, birthday, CURRENT_TIMESTAMP) >= ?', [$minAge])
->whereRaw('timestampdiff(YEAR, birthday, CURRENT_TIMESTAMP) <= ?', [$maxAge]);
})
->first();

注意:此答案假设您使用的是MySql

我不确定 MySql 的YEAR差异是否适合这里,因为它已经将 2 年 + 1 天的差异算作 3 年。但它应该给你一个寻找的方向。

最新更新