Support the ongoing development of Laravel.io →
Database Eloquent

I have an parent->child relationship where a confirmed column in the pivot table exists. Both the child and parent are User models so the parent->child is an relationship to itsself with the pivot table parent_user to set the relation.

Errors pops up when im doing:

User::has('childs')->with('childs')->get();

Relation in User model:

public function childs(){
     return $this->belongsToMany('User', 'parent_user', 'parent_id', 'user_id')
     ->wherePivot('confirmed', 1);
}

Error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'parent_user.confirmed' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and (select count(*) from `parent_user` as `self_7c0a80396bef95fb624cb427df01f6b1` where `users`.`deleted_at` is null and `self_7c0a80396bef95fb624cb427df01f6b1`.`parent_id` = `users`.`id` and `users`.`deleted_at` is null and `parent_user`.`confirmed` = 1) >= 1)

Im running on version 4.2.11

Last updated 3 years ago.
0

Edit seems bugged, so im gonna write the edit here:

Eloquent is referencing parent_user in the sub-query but it isn't using it for the confirmed column. Anyone knows why eloquent is doing this or how I can fix this?

Last updated 3 years ago.
0

Why?
Probably because of the withPivot inside the childs().
How to fix it?
You could remove the withPivot, and instead of has('child') use

->whereHas('childs', function($shildsQuery){
    $childsQuery->where('comfirmed', '=', true);
})->...

You can also try make a scope for the confirmed column. Maybe it will work solve your problem.

Last updated 3 years ago.
0

Hello,

I have the same problem. Did you find any solution for this?

Thank you!!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.