Laravel:如何从急切的加载中获得结果?

时间:2014-06-12 14:54:17

标签: php laravel eloquent

我的控制器中有这个代码:

$users = User::->get();
$users->load('company');

查询:

select * from `users` order by `lastname` asc

select * from `companies` where `companies`.`id` in ('4', '9')

如何从第二个查询中获取结果(集合)?

1 个答案:

答案 0 :(得分:0)

这里似乎你有一个User belongsTo Company关系,所以结果(不是急切,但在这种情况下很懒)加载是一个Model,而不是Collection

话虽如此,您可以通过这种方式访问​​相关模型:

foreach ($users as $user)
{
  $user->company;
}

现在,要获取这些公司的Collection,您需要这样做:

$users = User::all(); // or User::someChainedMethodsHere->get();
$companyIds = $users->fetch('company_id')->toArray(); // assuming company_id is the foreign key
$companies = Company::whereIn('id', $companyIds)->get(); // assuming id is the PK
// returns the Collection you wanted