在渴望加载中添加多个关系

时间:2018-10-29 19:15:41

标签: php laravel eloquent

我的应用程序:在我的应用程序中,用户可以预测即将到来的足球比赛的得分。因此,userpredictions之间基本上存在关系,但是prediction和我的Match model之间也存在关系。目前,我在预测表中添加了homeTeamNameawayTeamName,但这并不是必需的,因为我将match_id存储在了预测表中。我想基于我的预测表中的match table从我的match_id中加载团队名称,而不是在预测表中添加名称。

这是我的关系:

匹配模型

class Match extends Model
{
    public function Predictions() {

        return $this->hasMany('App\Prediction'); // one match has many predictions
    }
}

预测模型

class Prediction extends Model
{
   public function User() {

       return $this->belongsTo('App\User'); // prediction belongs to a user
   }

   public function Match() {

       return $this->belongsTo('App\Match', 'match_id', 'match_id'); // prediction belongs to a match
   }
}

用户模型

class User extends Authenticatable
{
    public function Predictions() {

        return $this->hasMany('App\Prediction'); // a user has many predictions
    }

}

对此查询使用延迟加载

public function showPredictions() {
    \DB::enableQueryLog();
    $user = Auth::user();

    $user->load('predictions', 'predictions.match'); 

    dd(\DB::getQueryLog());

    return view('predictions', compact('user'));
}

输出

array:3 [▼
  0 => array:3 [▼
    "query" => "select * from `users` where `id` = ? limit 1"
    "bindings" => array:1 [▼
      0 => 1
    ]
    "time" => 13.0
  ]
  1 => array:3 [▼
    "query" => "select * from `predictions` where `predictions`.`user_id` in (?)"
    "bindings" => array:1 [▼
      0 => 1
    ]
    "time" => 1.0
  ]
  2 => array:3 [▼
    "query" => "select * from `matches` where `matches`.`id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    "bindings" => array:10 [▼
      0 => 233133
      1 => 233134
      2 => 233135
      3 => 233136
      4 => 233137
      5 => 233138
      6 => 233139
      7 => 233140
      8 => 233141
      9 => 233142
    ]
    "time" => 1.0
  ]
]

2 个答案:

答案 0 :(得分:2)

要急于加载嵌套关系,可以使用“点”语法

$user->load('predictions', 'predictions.match')->where('status', 'SCHEDULED'); 

答案 1 :(得分:0)

尝试一下

lista = [1,2,3,4,5,6,7,8,9,10]
listres = [0001,0010,0011,0100,...]

或者如果两个表中都有$user->load([ 'predictions.match' => function ($query) { $query->where('status', 'SCHEDULED'); } ]); 列:

status
相关问题