【发布时间】:2019-01-04 20:29:46
【问题描述】:
我正在尝试获取用户数据,他们将部门值放入数组中,以便我可以对其进行分组并计算有多少用户属于同一部门。
用户表:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
部门表:
Schema::create('departments', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
});
分配表:
Schema::create('assignments', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('department_id')->nullable();
$table->foreign('department_id')->references('id')->on('departments');
});
public function setDepartment($users)
{
$departmentArray = [];
$users = DB::table('users')
->leftJoin('assignments','assignments.user_id','=','users.id')
->leftJoin('departments','assignments.department_id','=','department.id')
->select('assignments.id as assignments',
'assignments.name as assignment_name',
'departments.id as dept_id',
'departments.name as dept_name',
'users.id as user_id',
'users.name as user_name'
)
->where('user_id','=',$users->id)
->get();
foreach($users as $user) {
$assignments = $user->assignments;
$dept_id = $user->dept_id;
$departmentArray[$user->dept_id] = $user->dept_name;
}
$users->department = $departmentArray;
$users->dept_id = $dept_id;
}
}
然后每当我尝试这样称呼它时:
public function index() {
$users = DB::table('users')->get();
$users = $this->setDepartment($users);
return view('/users/list', [
'users' => $users
]);
}
我收到了
“试图获取非对象的属性'user_id'”
【问题讨论】:
-
我想澄清一些部分,你想得到同一部门下的所有用户对吗?
-
你能检查出是哪一行导致了这个错误吗?
-
@Miggy 说得对。
-
您的模型中的这些表是否存在关系?如果是这样,你能把它们贴出来吗?