我刚刚开始使用Laravel队列,并且不知道这是否可以在Laravel中完成
而不是这样做有效...
$test1 = Test1::where('fieldname', $value)->exists();
$test2 = Test2::where('fieldname', $value)->exists();
$test3 = Test3::where('fieldname', $value)->exists();
$test4 = Test4::where('fieldname', $value)->exists();
我想创建一个模型类和字段名数组,然后遍历数组...
$classes = [
'Test1' => 'fieldname',
'Test2' => 'fieldname',
'Test3' => 'fieldname',
'Test4' => 'fieldname',
];
foreach($classes as $class => $field) {
$class::where($field, $groupid)->exists();
}
但是当我运行我的工作时,我收到以下消息并且它已经死了
Class' Test1'找不到
我想在循环中做其他事情,这会减少我的代码并且看起来更具可读性。
你能不能像我试过的那样使用变量来调用类?
这是我的代码
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use \App\Models\Test;
class ImportProductGroupCrm implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $product;
public $tries = 1;
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$classes = [
'Test' => 'field-Name',
];
foreach($classes as $class => $field) {
$class::where($field, $groupid)->exists();
}
}
}
答案 0 :(得分:1)
您必须指定整个班级名称或使用::class
:
$classes = [
'App\Test1' => 'fieldname',
Test1::class => 'fieldname',
];