how to join 3 table wherehas eloquent using laravel

335 Views Asked by At

for example I have 3 tables and that tables has a relation,

Table A

  • id
  • name

Table B

  • id
  • tableId_A
  • tableId_C

Table C

  • id
  • name

i'm using table C but i want to search items by request name that have the same name as in table A using query eloquent and this is the query, i'm using a laravel

$this->model->query()
            ->withWhereHas('tableB', function($query) use ($names) {
            $query->tableB->where('name', 'LIKE', "%{$names}%");})

how to fix it using eloquent where has used 3 tables relation?

1

There are 1 best solutions below

0
JS TECH On

I think your relation name should be tableA not tableB.

public function tableA() 
{
    return $this->belongsToMany(TableAModel::class, 'TableB', 'tableId_C', 'tableId_A')
        ->where('TableA.status', CoreStatusEnum::ACTIVE); 
}

And your query goes like this..

$this->model->query()
    ->withWhereHas('tableA', function($query) use ($names) {
        $query->where('name', 'LIKE', "%{$names}%");
    })
    ->get();