【问题标题】:Pass Eloquent Model As An Closure Argument In PHP在 PHP 中将 Eloquent 模型作为闭包参数传​​递
【发布时间】:2017-01-19 03:34:01
【问题描述】:

我在 laravel 应用程序之外使用 Laravel Illuminate/Database。我正在尝试将 Eloquent 模型作为我的闭包参数传​​递,但它会引发错误。可能是我错误地传递了它。我的代码如下:

      // Create a dummy subject (This is working absolutely fine)
        SubjectModel::create(array(
            'title' => 'Mathematics',
            'description' => 'Math Subject',
            'slug' => 'math',
            'ka_url' => 'http://khanacademy.org/math'
        ));


        $scrapper = new SubjectScrapper();
        $scrapper->setUrl('');

这不起作用。 SubjectModel 未在以下闭包中传递

          $scrapper->runScrapper(function($subjects) use ($scrapper, SubjectModel $subjectModel) {

            if(!empty($subjects))
            {
                foreach ($subjects as $subject) {
                    $urlParts = explode('/', $subject['url']);
                    $slug = end($urlParts);
                    $subjectModel::create(array(
                        'title'     => $subject['subject_name'],
                        'slug'      => $slug,
                        'ka_url'    => $scrapper->getBaseUrl().$subject['link'],
                    ));
                }
            }
        });

谁能告诉我如何完成这项任务。

【问题讨论】:

    标签: eloquent php-closures


    【解决方案1】:

    试试这个。无需在闭包中传递对象

    $scrapper = new SubjectScrapper();
    $scrapper->setUrl('');
    $scrapper->runScrapper(function($subjects) use ($scrapper, $output) {
    
      SubjectModel::create(array(
          'title'     => 'Math',
          'slug'      => 'math',
          'ka_url'    => 'http://math'
      ));
    
        $output->writeln('<info>Total Subjects Scrapped:: '.count($subjects).'</info>'.PHP_EOL);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2016-08-25
      • 1970-01-01
      相关资源
      最近更新 更多