我在我的Company
应用程序中定义了Contact
模型和Laravel 5.4
模型,它们都有很多关系。因此,例如联系人模型具有:
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}
现在我有一个数据集,我想要提取所有联系人数据以及我正在使用的公司详细信息:
public function getData()
{
$contacts = Contact::all();
foreach($contacts as $contact)
{
$getCompany = $contact->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first();
$getCompany->contacts = Company::find($getCompany->id)->contacts;
$contact->company = $getCompany;
$contact->companies_interested = json_decode($contact->companies_interested);
$companies = [];
if($contact->companies_interested)
{
foreach($contact->companies_interested as $companiesInterested)
{
$getCompany = Company::withTrashed()->find($companiesInterested);
$companies[] = array(
'value' => $getCompany->id,
'label' => $getCompany->name
);
}
$contact->companies_interested = json_encode($companies);
}
}
return response()->json([
'model' => $contacts
], 200);
}
这适用于小型数据集,但是当使用大量数据时它会失败(大约10,000个字段),我想在大数据集时加载php memory fails
。我正在浏览Laravel
个文档以找出解决方案,并了解了chunk()
和cursor()
方法,有人可以指导我在这个问题上可以做些什么,或者可以采用什么方法克服这一点。
由于
答案 0 :(得分:5)
我建议您测试两种方法,以获得系统的某些怪癖。
组块:
它将" paginate"你的查询,这样你就可以使用更少的内存。
`
public function getData() {
Contact::chunk(1000, function ($contacts) {
foreach ($contacts as $contact) {
//rest of your code...
}
});
}
`
光标:
您将使用PHP生成器逐个搜索您的查询项。
`
public function getData() {
foreach (Contact::cursor() as $contact) {
//rest of your code...
}
}
`
要获得更详细的说明,请参阅此答案:What is the difference between laravel cursor and laravel chunk method?
对于效果测试,请参阅此帖子:https://translate.google.com/translate?hl=en&sl=auto&tl=en&u=http%3A%2F%2Fqiita.com%2Fryo511%2Fitems%2Febcd1c1b2ad5addc5c9d