Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The whereHas method doesn't work for self relations #181

Open
wgcontrol opened this issue Nov 26, 2024 · 1 comment
Open

The whereHas method doesn't work for self relations #181

wgcontrol opened this issue Nov 26, 2024 · 1 comment

Comments

@wgcontrol
Copy link

I have a relation in my User model:

public function referrer(): BelongsTo
{
    return $this->belongsTo(
        User::class , 
        ['referrer_id', 'bot_id'], 
        ['id', 'bot_id']
    );
}

And when i call the whereHas method:

User::whereHas('referrer', fn ($query) => $query->whereKey(121));

I give this error:

[2024-11-26 12:49:33] local.ERROR: Array to string conversion {"exception":"[object] (ErrorException(code: 0): Array to string conversion at /www/wwwroot/matrix/vendor/awobaz/compoships/src/Database/Eloquent/Relations/BelongsTo.php:288)
[stacktrace]
#0 /www/wwwroot/matrix/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(254): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError()
#1 /www/wwwroot/matrix/vendor/awobaz/compoships/src/Database/Eloquent/Relations/BelongsTo.php(288): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->Illuminate\\Foundation\\Bootstrap\\{closure}()
#2 /www/wwwroot/matrix/vendor/awobaz/compoships/src/Database/Eloquent/Relations/BelongsTo.php(197): Awobaz\\Compoships\\Database\\Eloquent\\Relations\\BelongsTo->getRelationExistenceQueryForSelfRelation()
#3 /www/wwwroot/matrix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php(54): Awobaz\\Compoships\\Database\\Eloquent\\Relations\\BelongsTo->getRelationExistenceQuery()
@wgcontrol
Copy link
Author

I fix this error by chaging the BelongsTo class and overriding the getRelationExistenceQueryForSelfRelation method.

public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
{
    $query->select($columns)->from(
        $query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()
    );

    $query->getModel()->setTable($hash);

    $ownerKeys = (array) $this->ownerKey;
    $qualifiedForeignKeyNames = (array) $this->getQualifiedForeignKeyName();
    
    foreach ($ownerKeys as $index => $ownerKey) {
        return $query->whereColumn(
            $hash.'.'.$ownerKey, '=', $qualifiedForeignKeyNames[$index]
        );
    }

    return $query;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant