mikebronner / laravel-model-caching

Eloquent model-caching made easy.
MIT License
2.22k stars 212 forks source link

Add expressionToString to getOtherClauses #451

Closed padre closed 6 months ago

padre commented 1 year ago

Fix exception: Object of class Illuminate\Database\Query\Expression could not be converted to string

Related: https://github.com/GeneaLabs/laravel-model-caching/issues/441

Eloquent query that caused the bug, for example:


$this
            ->vigilances()
            ->has('investigations', '=', 1);

If i try to dump $where variable and got:

array:5 [▼ // vendor/genealabs/laravel-model-caching/src/CacheKey.php
  "type" => "Basic"
  "column" => Illuminate\Database\Query\Expression {#4958 ▼
    #value: "(select count(*) from `investigations` inner join `investigation_vigilance` on `investigations`.`id` = `investigation_vigilance`.`investigation_id` where `vigilances`.`id` = `investigation_vigilance`.`vigilance_id` and `investigations`.`deleted_at` is null) ◀"
  }
  "operator" => "="
  "value" => Illuminate\Database\Query\Expression {#4960 ▼
    #value: 1
  }
  "boolean" => "and"
]
padre commented 1 year ago

@mikebronner can you merge this, please?

Thanks!

mikebronner commented 1 year ago

@padre could you add a test that covers this specific use-case? I also made some small tweaks to the code.

padre commented 1 year ago

@mikebronner Thank you very much for your quick response and your attention, but I don't think I have the necessary knowledge to add a test.

The exception occurs when I use ->has() in a belongsToMany relationship.

class Investigation extends Model
{
    public function vigilances()
    {
       return $this->belongsToMany(Vigilance::class);
    }
}

class Vigilance extends Model
{
    public function investigations()
    {
        return $this->belongsToMany(Investigation::class);
    }
}
$investigation
->vigilances()
->has('investigations', '=', 1)
->get();

This causes in the method "getOtherClauses(array $where)" in the statement

$column .= isset($where["column"]) ? $where["column"] : "";

the exception "Object of class IlluminateDatabaseQueryExpression could not be converted to string".

If i try to dump $where variable and got:

array:5 [
  "type" => "Basic"
  "column" => Illuminate\Database\Query\Expression {#3051 ▼
    #value: "(select count(*) from `investigations` inner join `investigation_vigilance` on `investigations`.`id` = `investigation_vigilance`.`investigation_id` where `vigilances`.`id` = `investigation_vigilance`.`vigilance_id` and `investigations`.`deleted_at` is null) ◀"
  }
  "operator" => "="
  "value" => Illuminate\Database\Query\Expression {#3053 ▼
    #value: 1
  }
  "boolean" => "and"

Thank you very much for your dedication.