我的项目中有 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”在 where 子句中不明确(SQL:从存在的专业中选择 *(从用户内部连接 user_professions 上选择 *user.id = user_professions.user_id其中professions.id = user_professions.profession_id 和 id in (11, 43, 82)))
我的代码哪里有错误,我该如何解决?