0

私のプロジェクトには 3 つのモデルがあります。

ユーザーモデル コード:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [];

    public function professions()
    {
        return $this->belongsToMany('App\Models\Profession', 'user_professions');
    }
}

職業モデルコード

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Profession extends Model
{
    protected $guarded = [];

    public function users()
    {
        return $this->belongsToMany('App\Models\User', 'user_professions');
    }
}

移行:

$table->id();
$table->string("name");
$table->timestamps();

UserProfessionモデルコード

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserProfession extends Model
{
    //
}

移行:

$table->id();
$table->foreignId('user_id')
  ->constrained()
  ->onDelete('cascade');
$table->foreignId('profession_id')
  ->constrained()
  ->onDelete('cascade');

このコードを試して、ユーザーを名前で検索し、そこに職業名を取得してから、その職業のユーザーを数えます。

コード:

$query = $request->get("query");
$users = User::where("name", "like", "%".$query."%");
$userIds = $users->get()->pluck("id")->toArray();

$professions = Profession::whereHas("users", function($q) use($userIds) {
    $q->whereIn('id', $userIds);
})->get()->toArray();

次のメッセージでエラーが発生します。

Illuminate\Database\QueryException: SQLSTATE[23000]: 整合性制約違反: 1052 列 'id' in where 句があいまいです (SQL: select * from Professions where exists (select * from users inner join user_professions on users.id = user_professions.user_idここで、professions.id = user_professions.profession_id および id in (11, 43, 82)))

コードのどこにエラーがあり、どのように修正できますか?

4

1 に答える 1