eloquent-power-joins icon indicating copy to clipboard operation
eloquent-power-joins copied to clipboard

Can't seem to filter when using power join

Open duncanmcclean opened this issue 2 years ago • 0 comments

We're attempting to use this package to easily swap out our queries written with whereHas to use joins instead.

However, when we went to change some of our queries to use the powerJoinWhereHas method, we see that the join is there in the SQL query but we can't see the ->whereIn('bed_types.id', $ids) bit in our SQL query anywhere.

Code

// app/Models/Product.php

public function scopeHasBedType($query, $id)
{
    $ids = Arr::wrap($id);

    return $query->powerJoinWhereHas('bedTypes', function ($query) use ($ids) {
        $query->whereIn('bed_types.id', $ids);
    });
}

public function bedTypes()
{
    return $this
        ->belongsToMany(BedType::class)
        ->using(BedTypeProduct::class);
}
// app/Models/BedType.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Rennokki\QueryCache\Traits\QueryCacheable;
use Spatie\EloquentSortable\SortableTrait;

class BedType extends Model
{
    use HasFactory;
    use SortableTrait;
    use QueryCacheable;

    public $sortable = [
        'order_column_name' => 'sort_order',
        'sort_when_creating' => true,
    ];

    protected $guarded = [];

    /**
     * Invalidate the cache automatically
     * upon update in the database.
     *
     * @var bool
     */
    protected static $flushCacheOnUpdate = true;

    /**
     * Specify the amount of time to cache queries.
     * Do not specify or set it to null to disable caching.
     *
     * @var int|\DateTime
     */
    public $cacheFor = 86400;

    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}

Table Structure

bed_types

  • id
  • name
  • created_at
  • updated_at
  • sort_order

bed_type_product

  • id
  • bed_type_id
  • product_id
  • created_at
  • updated_at

Additional information

  • Laravel 9.31.0
  • PHP 8.1.8
  • Power Joins 2.6.4

duncanmcclean avatar Oct 18 '22 11:10 duncanmcclean