T
T
timehollyname2022-02-27 11:18:27
Laravel
timehollyname, 2022-02-27 11:18:27

Can't filter many to many entries?

There are 4 models:

class WebSite:
  id
  name

class Module:
  id
  name

  public function moduledatabase() {
        return $this->hasMany(\App\Models\ModuleDatabase::class, 'module_id');
    }

class ModuleDatabase:
  id
  name
  module_id

  public function websites() {
      return $this->belongsToMany(\App\Models\WebSite::class, 'module_database_web_sites');
  }

class ModuleDatabaseWebSite:
  id
  web_site_id
  module_database_id


The question is how do I find entries in the `ModuleDatabase` model that have a site with id = 1; Tried to get it in the following ways:

$module->moduledatabase()->with('websites', function($query) {
    $query->where('id', 1);
})->get();

$module->moduledatabase()->whereRelation('websites', 'id', '=', 1)->get();

$module->moduledatabase()->whereDoesntHave('websites', function($query) {
    $query->where('id', 1);
})->get();


But it doesn't work, it throws an error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select `web_sites`.*, `module_database_web_sites`.`module_database_id` as `pivot_module_database_id`, `module_database_web_sites`.`web_site_id` as `pivot_web_site_id` from `web_sites` inner join `module_database_web_sites` on `web_sites`.`id` = `module_database_web_sites`.`web_site_id` where `module_database_web_sites`.`module_database_id` in (1, 2, 3) and `id` = 1 order by `id` desc)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question