php laravel用的多不,php-使用多个Laravel范围进行关系过滤时出现...

我正在使用Laravel 5.6,并且正在尝试过滤User模型中的关系.用户可以参加课程,这些课程具有要点.

用户可以通过参加课程获得这些积分.这是BelongsToMany关系.

我尝试在此用户模型中创建一个范围,该范围仅包括几年内参加的课程.

/**

* Retrieves the courses which the user has attended

*/

public function attendedCourses()

{

return $this->belongsToMany(Course::class, 'course_attendees');

}

/**

* Searches the user model

*

* @param \Illuminate\Database\Eloquent\Builder $builder

* @param array $years

*

* @return \Illuminate\Database\Eloquent\Builder

*/

public function scopeAttendedCoursesInYears(Builder $builder, array $years)

{

# Filter on the years

$callback = function($q) use ($years) {

foreach ($years as $year) {

$q->year($year);

}

};

return $builder->with(['attendedCourses' => $callback]);

}

在我的课程模型中,我有一个范围可以过滤该课程所在的年份.

public function scopeYear(Builder $query, int $year)

{

return $query->whereYear('end_date', $year);

}

希望有了这个有人参与的课程年度范围,我希望我可以使用课程模型上的其他范围,通过汇总课程点数来为每个用户计算点数.

public function scopeExternal(Builder $query, bool $flag = true)

{

$categoryIsExternal = function($query) use ($flag) {

$query->external($flag);

};

return $query->whereHas('category', $categoryIsExternal);

}

在我的CourseCategory模式中,范围如下所示:

/**

* Scope a query to only include external categories.

*

* @param \Illuminate\Database\Eloquent\Builder $query

*

* @param bool $flag

*

* @return \Illuminate\Database\Eloquent\Builder

*/

public function scopeExternal(Builder $query, $flag = true)

{

return $query->where('type', '=', $flag ? 'Extern' : 'Intern');

}

为了计算这个,我尝试做这样的事情.

# Retrieve all the active users

$users = User::all()->attendedCoursesInYears($years);

$test = $users->find(123);

# Calculate the points

$test->attendedCourses()->external(false)->sum('points');

但是,这返回了所有课程的总和.

如我所见,使用范围是这里的唯一选择.我想使用这样的访问器从这些值创建自定义属性.这样,我可以轻松地对计算得出的值进行排序.

/**

* The users internal course points

*

* @param array $years The years to look for attended courses

*

* @return float

*/

public function getInternalPointsAttribute() : float

{

return $this->attendedCourses()->external(false)->sum('points');

}

唯一的问题是年份过滤器.我希望我可以像第一个示例一样在调用访问器之前过滤User集合.

我在这里做错了什么?

我目前正在使用此解决方法.这似乎很糟糕,因为我要重复很多代码.

/**

* @param \Illuminate\Database\Eloquent\Builder $builder

*

* @param array $years

*

* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder

*/

public function scopeWithPoints(Builder $builder, array $years = [])

{

# Join all columns

$builder->join('user_roles', 'users.role_id', '=', 'user_roles.id')

->leftJoin('course_attendees', 'users.id', '=', 'course_attendees.user_id');

# Join the course table for the years

$builder->leftJoin('courses', function(JoinClause $join) use ($years) {

# Join the courses table with year filters

$join->on('course_attendees.course_id', '=', 'courses.id');

# Apply the filters if available

!empty($years) and $join->whereIn(DB::raw('YEAR(courses.end_date)'), $years);

});

# Select the columns

$builder->select('users.*')->groupBy('users.id');

# Sums

$internalPoints = 'SUM(courses.points_internal)';

$externalPoints = 'SUM(courses.points_external)';

# Select the points

$builder->selectRaw('COALESCE(' . $internalPoints . ', 0) as internal_points');

$builder->selectRaw('COALESCE(' . $externalPoints . ', 0) as external_points');

$builder->selectRaw('COALESCE(' . $internalPoints . ' + ' . $externalPoints . ', 0) as total_points');

# Sum up the course points

return $builder;

}

我的数据库结构的迁移可以在这里找到.

Schema::create('course_attendees', function(Blueprint $table)

{

$table->integer('id', true);

$table->integer('user_id')->index('course_attendees_users_id_fk');

$table->integer('course_id')->index('course_attendees_courses_id_fk');

$table->boolean('mijnafas');

});

Schema::create('courses', function(Blueprint $table)

{

$table->integer('id', true);

$table->string('title');

$table->string('subject');

$table->string('presenter');

$table->date('start_date')->nullable()->comment('Set to not null later');

$table->date('end_date')->nullable();

$table->decimal('points', 4)->nullable();

$table->string('location');

$table->timestamps();

});

Schema::create('users', function(Blueprint $table)

{

$table->integer('id', true);

$table->string('first_name')->nullable();

$table->string('last_name')->nullable();

$table->timestamps();

});

Schema::table('course_attendees', function(Blueprint $table)

{

$table->foreign('course_id', 'course_attendees_courses_id_fk')->references('id')->on('courses')->onUpdate('RESTRICT')->onDelete('RESTRICT');

$table->foreign('user_id', 'course_attendees_users_id_fk')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('RESTRICT');

});

我注意到,仅在调用$test-> attendedCourses时,它会检索已过滤的集合.问题是我无法在此范围内应用.

问题

>为什么不对过滤后的集合求和?

>如何使它能够相应地过滤此集合?

### 回答1: 在 Laravel 使用 Goutte 和 Guzzle 实现一个简单的爬虫非常容易,下面是一个简单的示例,步骤如下: 1. 安装 Guzzle 和 Goutte 在 Laravel 项目使用 Composer 安装 Guzzle 和 Goutte: ``` composer require guzzlehttp/guzzle composer require symfony/dom-crawler ``` 2. 创建一个命令 在 Laravel ,您可以使用 `make:command` Artisan 命令创建一个命令来运您的爬虫,例如: ``` php artisan make:command Spider ``` 这将在 `app/Console/Commands` 目录创建一个名为 `Spider` 的新命令。 3. 编写命令代码 在 `app/Console/Commands/Spider.php` 文件,您可以编写以下代码: ```php <?php namespace App\Console\Commands; use Illuminate\Console\Command; use GuzzleHttp\Client; use Goutte\Client as GoutteClient; class Spider extends Command { protected $signature = 'spider:run {url}'; protected $description = 'Run a simple spider.'; public function handle() { $url = $this->argument('url'); $client = new Client(); $goutte = new GoutteClient(); $response = $client->request('GET', $url); $crawler = $goutte->request('GET', $url); $crawler->filter('a')->each(function($node) { $link = $node->attr('href'); $this->info($link); }); } } ``` 在这个例子,我们首先获取通过命令传递的 URL,然后使用 Guzzle 发送一个 HTTP GET 请求获取页面内容。接下来,我们使用 Goutte 解析页面并找到其的所有链接。 4. 运命令 现在,您可以使用以下命令运您的爬虫: ``` php artisan spider:run http://example.com ``` 这将输出页面的所有链接。 这只是一个简单的示例,您可以根据需要扩展它。例如,您可以编写代码来在数据库存储页面内容,或者使用更高级的爬虫技术来提取更有用的信息。 ### 回答2: 使用PHPLaravel框架来构建一个简单爬虫可以使用Goutte和Guzzle这两个库来实现。下面是一个使用Goutte和Guzzle来构建简单爬虫的步骤。 首先,我们需要安装Goutte和Guzzle库。在Laravel项目的根目录下运以下命令: ``` composer require goutte/goutte guzzlehttp/guzzle ``` 安装完成后,我们就可以开始编写爬虫代码了。首先在控制器引入Goutte和Guzzle的命名空间: ``` use Goutte\Client; use GuzzleHttp\Client as GuzzleClient; ``` 接下来,我们可以在控制器编写一个方法来实现爬虫功能。以下是一个简单的例子: ```php public function crawl() { // 创建一个Goutte的Client实例 $client = new Client(); // 使用Guzzle来实现异步请求 $guzzleClient = new GuzzleClient(['timeout' => 60]); $client->setClient($guzzleClient); // 发起请求并获取响应 $crawler = $client->request('GET', 'http://example.com'); // 使用CSS选择器来提取需要的数据 $crawler->filter('h1')->each(function ($node) { echo $node->text()."\n"; }); } ``` 在上面的例子,我们首先创建了一个Goutte的Client实例,并使用Guzzle作为底层的HTTP客户端。然后,我们发起了一个GET请求,并使用CSS选择器来过滤需要的数据。在这个例子,我们提取了页面的所有h1标签的文本内容,并打印出来。 最后,将上述代码放在你的控制器的方法,并通过路由调用该方法即可执爬虫功能。 以上就是使用PHPLaravel框架、Goutte和Guzzle实现简单爬虫的基本步骤。当然,具体的爬虫功能和数据提取都可以根据实际需要进行更进一步的定制。 ### 回答3: 使用php laravel可以很方便地使用Goutte和Guzzle来实现简单的爬虫功能。Goutte是一个用于Web页面抓取的PHP库,而Guzzle是一个功能强大的HTTP客户端。下面是一个使用Goutte和Guzzle实现简单爬虫的示例: 首先,确保已经安装了laravel,并且在composer.json已经添加了goutte和guzzle的依赖。 在需要使用爬虫的地方,可以创建一个新的控制器或者在已有的控制器添加一个方法。在这个方法,可以使用Goutte来载入目标网页并选择需要抓取的元素。 ```php use Goutte\Client; public function crawl() { $url = 'http://example.com'; // 要抓取的网页URL $client = new Client(); $crawler = $client->request('GET', $url); // 选择需要抓取的元素 $crawler->filter('h1')->each(function ($node) { echo $node->text()."\n"; }); // 使用Guzzle发送GET请求(可选) $client = new \GuzzleHttp\Client(); $response = $client->request('GET', $url); $body = $response->getBody(); // 进一步处理网页内容 } ``` 上述代码使用Goutte首先发送GET请求到指定的URL,然后使用filter方法选择需要抓取的元素,这里选择了`<h1>`标签,并使用each方法将抓取到的内容进行输出。 这种选择器的语法类似于jQuery,可以根据具体需求选择不同的元素进行抓取。 如果需要进一步处理网页内容,例如使用Guzzle发送HTTP请求,请先在控制器的顶部添加`use GuzzleHttp\Client;`,然后使用Guzzle的Client类发送HTTP请求。 最后,可以在路由定义一个对应的路由,指向上面创建的控制器和方法,以便在浏览器访问。 这只是一个简单的爬虫示例,实际的使用会根据具体需求进行更多的定制和功能拓展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值