Php 使用whereHas雄辩的关系查询
我有以下表格: 使用者 区域 区域用户Php 使用whereHas雄辩的关系查询,php,mysql,database,laravel,eloquent,Php,Mysql,Database,Laravel,Eloquent,我有以下表格: 使用者 区域 区域用户 Schema::create('area_user', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('us
Schema::create('area_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('area_id')->unsigned();
$table->foreign('area_id')->references('id')->on('areas');
});
建筑物
Schema::create('buildings', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('symbol')->nullable();
$table->integer('area_id')->unsigned();
$table->foreign('area_id')->references('id')->on('areas')->onDelete('cascade');
$table->integer('building_type')->unsigned();
$table->foreign('building_type')->references('id')->on('building_types');
$table->timestamps();
});
用户模型:
public function areas()
{
return $this->belongsToMany('App\Area');
}
面积模型:
public function users(){
return $this->belongsToMany('App\User');
}
建筑模型:
public function area(){
return $this->belongsTo('App\Area','area_id');
}
如何在用户模型中编写查询,以返回通过用户指定区域(area_User table)分配给用户的所有建筑
我尝试了这个,但它返回了一个错误
Building::whereHas('area', function ($q) {
$q->whereHas('users', function ($q) {
$q->where('id', auth()->id());
});
})->get();
错误:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `buildings` where exists (select * from `areas` where `buildings`.`area_id` = `areas`.`id` and exists (select * from `users` inner join `area_user` on `users`.`id` = `area_user`.`user_id` where `areas`.`id` = `area_user`.`area_id` and `id` = 11))) (View: C:\xampp\htdocs\hse\resources\views\observations\form_observation.blade.php) (View: C:\xampp\htdocs\hse\resources\views\observations\form_observation.blade.php)
您可以通过在where子句中指定表格来解决歧义: 改变
$q->where('id', auth()->id());
到
在用户模型App\User::buildings中使用此查询时显示错误必须返回关系实例。(视图:C:\xampp\htdocs\hse\resources\views\observations\form_observation.blade.php在视图文件中=============foreach(Auth::user()->建筑物为$b){{{{$b->name}#endforeach@user2873860看起来你遇到了新问题,应该问一个新问题。好的,我会发布一个新问题
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `buildings` where exists (select * from `areas` where `buildings`.`area_id` = `areas`.`id` and exists (select * from `users` inner join `area_user` on `users`.`id` = `area_user`.`user_id` where `areas`.`id` = `area_user`.`area_id` and `id` = 11))) (View: C:\xampp\htdocs\hse\resources\views\observations\form_observation.blade.php) (View: C:\xampp\htdocs\hse\resources\views\observations\form_observation.blade.php)
$q->where('id', auth()->id());
$q->where('users.id', auth()->id());