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”在 where 子句中不明确(SQL:从存在的专业中选择 *(从用户内部连接 ​​user_professions 上选择 *user.id = user_professions.user_id其中professions.id = user_professions.profession_id 和 id in (11, 43, 82)))

我的代码哪里有错误,我该如何解决?

4

1 回答 1

2

有三个表usersuser_professions并且professions都有id列。

您需要指定您想要的表的 id:

$professions = Profession::whereHas("users", function($q) use($userIds) {
    $q->whereIn('users.id', $userIds); // specify the table name
})->get()->toArray();
于 2020-03-13T08:01:35.550 回答