binggle's avatar

How to get relation with condition and ofMany ?

I have two models Banner/BannerLog

Banner has many BannerLog

banner_logs table has these field.

Schema::create('banner_logs', function (Blueprint $table) {
    $table->unsignedBigInteger('banner_id');
    $table->string('type')->default('view'); // view / click
    $table->integer('count')->default(0);

});

Models are

class Banner extends Model
{
    function views(){
        return $this->hasMany(BannerLog::class)->where('type', 'view')->ofMany('count', 'sum');
    }
}
class BannerLog extends Model
{
    function banner()
    {
        return $this->belongsTo(Banner::class);
    }

}

I want to get BannerLog view count following log_type.

$banner->views gives this.

Attempted to lazy load [views] on model [App\Models\Banner] but lazy loading is disabled.

Even though I comment Model::preventLazyLoading(true); line in AppServiceProvider.php, it gives me another error .

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::ofMany()

How can I get the view count from banner_logs on banner model together ?$_COOKIE

0 likes
2 replies
LaryAI's avatar
Level 58

You can use the sum() method on the BannerLog model to get the view count from the banner_logs table.

class Banner extends Model
{
    function views(){
        return $this->hasMany(BannerLog::class)
            ->where('type', 'view')
            ->sum('count');
    }
}

Please or to participate in this conversation.