Level 19
Have you tried using whereRelation?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have 3 models each mapping to a table as below
ModelA maps to table model_a
ModelB maps to table model_b
ModelC maps to table model_c
ModelA has one to many relationship with ModelB ModelA has one to many relationship with ModelC
the rough schema of all three models is as below
//table model_a
id | name | value_a
//table model_b
id | model_a_id | name | value_b
//table model_c
id | model_a_id | name | value_c
//in ModelA
public function c()
{
return $this->hasMany(ModelC::class);
}
//in ModelB
public function a()
{
return $this->belongsTo(ModelA::class);
}
I want to query data from model_b where model_a.value_a = model_b.value_b
//throws an SQL column error for model_a.value_a saying no column found in model_c
$result = ModelB::with([
"a",
"a.c" => function($query)
{
$query->whereColumn('value_c' ,'model_a.value_a' );
}
]);
//throws the same error as for above
$result = ModelB::with([
"a",
"a.c" => function($query)
{
$query->whereRaw('`value_c` =`model_a.value_a`' );
}
]);
I have also tried whereHas and withWhereHas but no luck.
What am I doing wrong here? Could anyone please help?
Thanks in advance :)
Please or to participate in this conversation.