首页 > 解决方案 > Laravel:使用 where inside(带模型)

问题描述

我有这个控制器:

public function user_predects()
{
    $matches=Match::with('Predect')->get();
    return ($matches);
}

它是这样获取 json 数据的:

[
    {
        "id": 1,
        "m_date": "2021-02-06 22:00:00",
        "home": "Turkey",
        "away": "Italy",
        "h_goals": 0,
        "a_goals": 0,
        "predect": [
          {
            "id": 3,
            "user_id": 10,
            "match_id": 1,
            "h_predect": 1,
            "a_predect": 1,
            "player_id": 1,
            "point": 0,
            "created_at": null,
            "updated_at": null
          },
          {
            "id": 4,
            "user_id": 9,
            "match_id": 1,
            "h_predect": 2,
            "a_predect": 1,
            "player_id": 1,
            "point": 0,
            "created_at": null,
            "updated_at": null

现在我想查看相同的 json 数据,但只针对一个用户,我使用了这个但不起作用:

public function user_predects($username)
{
    $user = User::where('username',$username)->get()
    $matches=Match::with('Predect')->where('Predect.user_id',$user[0]->id)->get();

    return ($matches);
}

如何查看一个用户的匹配模型和预测模型?

标签: phplaravelwhere-clausehas-many

解决方案


试试这个:

public function user_predects($username)
{
    $user = User::where('username',$username)->first()
    $matches = Match::with(['Predect' => function($query) use ($user) {
        return $query->where('Predect.user_id', $user->id);
    }])->get();

    return ($matches);
}

您还可以从官方文档中阅读有关约束 Eager Loading 的信息:Constraining Eager Loads


推荐阅读