我有这个错误
SQLSTATE [23000]:完整性约束违规:1052字段列表中的列'id'不明确(SQL:select id,followers.user_id as pivot_user_id,followers.follows_id as pivot_follows_id,followers.created_at as pivot_created_at,followers.updated_at as来自users.id = followers.follows_id的用户内部联接关注者的pivot_updated_at,其中followers.user_id = 1且following_id = 2 limit 1)
(查看:/Users/harshitsingh/Documents/logos/resources/views/users/index.blade.php) 这是我的UsersController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Image;
use Auth;
use Profile;
use App\Post;
use App\Notifications\UserFollowed;
class UsersController extends Controller
{
public function index()
{
$users = User::where('id', '!=', auth()->user()->id)->get();
return view('users.index', compact('users'));
}
public function profile(){
return view('profile');
}
public function update_avatar(Request $request){
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)
->resize(300, 300)
->save( public_path('/uploads/avatars/' . $filename )
);
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return redirect('/');
}
public function follow(User $user)
{
$follower = auth()->user();
if ($follower->id == $user->id) {
return back()->withError("You can't follow yourself");
}
if(!$follower->isFollowing($user->id)) {
$follower->follow($user->id);
// sending a notification
$user->notify(new UserFollowed($follower));
return back()->withSuccess("You are now friends with {$user->name}");
}
return back()->withError("You are already following {$user->name}");
}
public function unfollow(User $user)
{
$follower = auth()->user();
if($follower->isFollowing($user->id)) {
$follower->unfollow($user->id);
return back()->withSuccess("You are no longer friends with {$user->name}");
}
return back()->withError("You are not following {$user->name}");
}
public function notifications()
{
return auth()->user()->unreadNotifications()->limit(5)->get()->toArray();
}
public function show(Post $post, $id)
{
$user = User::findOrFail($id);
return view('user.profile', compact('user'));
}
}
我正在尝试用户与用户的关系 这是用户模型 `
public function followers()
{
return $this->belongsToMany(self::class, 'followers', 'follows_id', 'user_id')
->withTimestamps();
}
public function follows()
{
return $this->belongsToMany(self::class, 'followers', 'user_id', 'follows_id')
->withTimestamps();
}
public function follow($userId)
{
$this->follows()->attach($userId);
return $this;
}
public function unfollow($userId)
{
$this->follows()->detach($userId);
return $this;
}
public function isFollowing($userId)
{
return (boolean) $this->follows()->where('follows_id', $userId)->first(['id']);
}
`
答案 0 :(得分:2)
尝试学习如何阅读错误消息。
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field list is ambiguous
此消息告诉您有2个或更多id
字段,哪个SQL不知道哪个SELECT
。在您的UserController
代码中,代码似乎不在那里,您可能需要查看User
模型。
您必须更新
SELECT id ...
到
SELECT users.id ...