angular - Angular - “类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串
问题描述
我正在开发一个以 Angular 7 作为前端,Laravel 5.8 作为后端的项目。我想要的是,当 id = 1 的用户(管理员)登录时,他会看到一切。但是当其他用户登录时,他只能看到具有他的 user_id 的数据。
Laravel:后端
public function indexSmsmo()
{
if(Auth::user()->id == 1)
$smsmos = Smsmo::all();
else
$smsmos = Smsmo::where('user_id',Auth::user()->id);
return $smsmos;
}
我有用户表和其他表。其他表中有 user_id。
auth.service.ts
import { environment } from '../../environments/environment.prod';
import { User } from '../models/user';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public currentUser: User;
private readonly apiUrl = environment.apiUrl;
private environmentService: EnvironmentService;
constructor(
private http: HttpClient,
private router: Router)
{
}
onLogin(user: User): Observable<User> {
const request = JSON.stringify(
{ email: user.email, password: user.password }
);
return this.http.post(this.loginUrl, request, httpOptions)
.pipe(
map((response: User) => {
// Receive jwt token in the response
const token: string = response['access_token'];
// If we have a token, proceed
if (token) {
this.setToken(token);
this.getUser().subscribe();
}
return response;
}),
catchError(error => this.handleError(error))
);
}
在此之后我们有登录组件
登录组件.ts
ngOnInit() {
document.body.className = 'hold-transition login-page';
$(() => {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' /* optional */
});
});
// Set the return url
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/home';
this.authService.onLogout();
}
onSubmit(loginForm): void {
this.spinnerService.show();
this.authService.onLogin(this.user).subscribe(
(response) => {
this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})
this.router.navigate([this.returnUrl]);
},
(error) => {
this.spinnerService.hide();
this.error = error.error;
}
);
// Clear form fields
loginForm.reset();
}
当我使用 userId 1 登录时,一切正常。但是当我使用其他 userId 登录时,我遇到了这个错误:
httpErrorResponse 消息:“类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串
如果用户登录并且 user_id 为 1,他应该看到所有内容,但如果不是 1,他应该看到 user_id 等于登录 ID 的数据
我该如何解决这个问题?
解决方案
在您的index
方法中,如果 user is id === 1
,您将返回一个集合,因为您使用了all()
.
如果用户不是id === 1
,则您仅返回一个构建器对象,因为您没有完成查询:
$smsmos = Smsmo::where('user_id',Auth::user()->id);
应该
$smsmos = Smsmo::where('user_id',Auth::user()->id)->first(); // or get() if you want a collection
推荐阅读
- spring - 有人可以帮我解决语法吗?
- python - Cython 内存分配
- python - Python & SQLite 填充数据库函数崩溃
- git - 如何删除这个 git bash 未跟踪列表
- python - 关于日期时间的“LIKE”查询的 Django ORM 语法
- r - selectInput 小部件的条件更新
- angular - Angular > 在材质表中显示列和行
- vue.js - FilePond for Vue / Nuxt:动态设置服务器属性?
- c - 错误:下标值既不是数组也不是指针也不是向量
- python - 在 python 中使用 youtube-dl 下载带有自动编号的 Youtube-Playlist 会导致错误