【发布时间】:2020-06-25 05:17:58
【问题描述】:
我的项目中有 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();
用户职业型号代码
<?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 where 子句中的列“id”不明确 (SQL:从存在的职业中选择*(从用户中选择* 内部加入 user_professions on users.id = user_professions.user_id 其中professions.id = user_professions.profession_id 和 id in (11, 43, 82)))
我的代码哪里有错误,我该如何解决?
【问题讨论】:
-
$q->whereIn('id', $userIds);你需要问自己什么id?用户ID? Professions.id? -
在我的情况下,
$userIds中的用户 ID。我有逻辑错误? @Avi -
因为 laravel 不知道你想要哪个表的
id -
如何更正我的查询? @TsaiKoga
-
按照 Laravel 的约定创建表名
profession_user,这样可以省去一些麻烦。检查(也在这里非常)good practice.
标签: laravel relationship eloquent-relationship laravel-7