0

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?

Marc Jamal
  • 47
  • 1
  • 2
  • 12
  • did you use `many to many` relation? – JS TECH Aug 29 '22 at 10:15
  • yes i have used eloquent many to many this is the script: ``` public function tableB() { return $this->belongsToMany(TableAModel::class, 'TableB', 'tableId_C', 'tableId_A')->where('TableA.status', CoreStatusEnum::ACTIVE); } ``` – Marc Jamal Aug 29 '22 at 10:20

1 Answers1

0

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();
JS TECH
  • 1,556
  • 2
  • 11
  • 27