【发布时间】:2017-03-30 21:39:21
【问题描述】:
我正在尝试通过使用 Artisan 创建的自定义控制台命令执行一些逻辑,但我无法使用我的模型类并使用 Eloquent 进行查询。
当我使用 MyModel::all() 时,它将返回集合中的所有记录。这很好,除了我使用的模型有太多记录无法将它们全部加载到内存中。
我正在尝试使用
MyModel::where('id',$currentLoopId)->get();
这将返回一个空集合:(
我的控制台类如下:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\ProcessReferral;
use App\TargetUrl;
use App\Website;
class ProcessReferrals extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'process:referrals';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Process all outstanding records in process_referrals table';
protected $logArray = [];
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Start Processing Referrals');
$process_referrals = ProcessReferral::all();
$referral_count = count($process_referrals);
$this->info('Found '.$referral_count.' referral(s) that need processed');
foreach($process_referrals as $referral){
## 1. SEE IF REFERRAL WEBSITE IS ACTIVE AND VERIFIED IN AFFILIATE_WEBSITES. LOAD LAST FORCE UPDATE REFRESH CODES
########################################
$this->info('Processing Referral ID: '.$referral->id);
$this->info('Get Website from Affiliate Website Id: '.$referral->affiliate_website_id);
$websites = Website::where('id','=',$referral->affiliate_website_id)->get();
dd($websites);
... ( more Logic after I get website )
}
}
我的模型类如下:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Website extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'affiliate_websites';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
...
];
... ( Eloquent Relations )
}
数据库表:
id website_label referrals
------------------------------
1 Google UK 920685
2 Google U.S. 2940884
3 Google Germany 709603
正在处理的第一个虚拟数据记录:
id affiliate_website_id
-------------------------
2 3
终端输出
$ php artisan process:referrals
Start Processing Referrals
Found 300 referral(s) that need processed
Processing Referral ID: 2
Get Website from Affiliate Website Id: 3
Website(id->62) is Active.
Illuminate\Database\Eloquent\Collection {#901
#items: []
}
我尝试了几种不同的查询方式,包括 DB::select(),它返回我正在寻找的内容,但我无法使用该约定动态设置我正在搜索的 id。
我的模型在我的应用程序的其他任何地方都可以使用,我认为存在某种命名空间问题,但我完全不知道为什么它不起作用。
任何帮助将不胜感激!
【问题讨论】:
-
在您上面的代码中,您在查询
Website::where()中缺少get()是错字吗? -
是的,这是一个错字
标签: laravel-5 console eloquent laravel-5.3 laravel-artisan