带有多个关系的laravel数据库查询

时间:2019-09-01 18:56:15

标签: database laravel join query-builder

我想从数据库中加载某个年龄段用户的帖子。用户可以保存最小值(用户->配置文件-> 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();

Post.php

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

User.php

public function posts()
    {
      return $this->hasMany('App\Post');
    }

public function profile()
    {
      return $this->hasOne('App\Profile');
    }

profile.php

public function users()
    {
    return $this->belongsTo('App\User');
    }

这可以在哪里使用,还是必须为此使用联接? 如何加载相应的帖子?

1 个答案:

答案 0 :(得分:1)

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

// 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年。但这应该为您提供指导。