我在 foreach 循环中有一个 Eloquent 查询。
我的 League
模型是正确的,当我回显值时,我在循环内得到正确的 $match->league_id
。
我的数据库中有与 $match->league_id
相关的记录。
foreach ($matchesRaw as $k=>$match) {
$lg= League::find($match->league_id)->first();
echo $lg->name;
}
我的问题是我的代码只显示数据库中的第一行 ($lg->name
)。这意味着我的查询总是排在第一行。无论 $match->league_id
是什么,都会进入循环。我该如何解决这个问题?
最佳答案
你的问题是你像这样调用first
:
League::first();
是的,它总是位于该表的第一行。
这是因为您所做的与:
$leagueModel = League::find($someId); // returns model
$leagueModel->first() == League::first(); // returns the same model
相反,您只需调用 League::find($someId)
,根本不需要 first
。
关于php - Laravel 在循环中 Eloquent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27707970/