我正在尝试计算我的产品的观看次数。为此,我的products表中有一列view_count
。我正在尝试使用事件监听器来实现它。
这是我的活动代码:
ProductWasViewed.php
<?php namespace App\Events;
use App\Events\Event;
use App\Modules\Product\Models\Product;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ProductWasViewed
{
use SerializesModels;
public $product;
public function __construct(Product $product)
{
$this->product = $product;
}
public function broadcastOn()
{
return [];
}
}
这是我的听众代码
IncrementProductViewCount.php
<?php namespace App\Listeners;
use App\Events\ProductWasViewed;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Modules\Product\Models\Product;
class IncrementProductViewCount
{
public function __construct() { }
public function handle(ProductWasViewed $event)
{
$event->product->increment('view_count');
}
}
EventServiceProvider.php
数组:
'App\Events\ProductWasViewed' => [
'App\Listeners\IncrementProductViewCount',
],
我使用事件监听器的控制器:
public function singleProduct(Request $request)
{
$name = $request->name;
$product = DB::table('products')
->where('name' , '=', $name)
->where('status','=',1)
->first();
Event::fire(new ProductWasViewed($product));
}
我得到的错误:
类型错误:参数1传递给 App \ Events \ ProductWasViewed :: __ construct()必须是。的实例 App \ Modules \ Product \ Models \ Product,给出的stdClass实例
我该如何解决这个问题?请帮忙。
答案 0 :(得分:2)
Query Builder请求返回stdClass
个对象。您需要在此处使用Eloquent来获取Product
对象:
$product = Product::where('name', $name)->where('status', 1)->first();