我想从数据库中加载特定年龄用户的帖子。用户可以在他的个人资料中保存最小(users->profile->min_age) 和最大年龄(users->profile->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('App\User', 'user_id');
}
用户名
public function posts()
{
return $this->hasMany('App\Post');
}
public function profile()
{
return $this->hasOne('App\Profile');
}
配置文件
public function users()
{
return $this->belongsTo('App\User');
}
这是否适用于何处或我是否必须为此使用连接?如何加载相应的帖子?
您可以将此约束添加到您的帖子查询中:
// 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
我不确定YEAR
MySql的差异是否适合于此,因为它将 2 年 + 1 天的差异计算为 3 年。但它应该给你一个寻找的方向。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句