Laravel 跟随控制器关系错误



我正在制作FollowController,我有两个表following_users表和following_user_item表。当身份验证current_user想要跟踪用户时,用户的 ID 将存储在表中following_users其关系表存储current_user_id和following_user_id(即表following_users ID(。下面是架构。

following_users_table

public function up()
{
Schema::create('following_users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users');
$table->timestamps();
});
}

following_user_item_table

public function up()
{
Schema::create('following_user_items', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('following_users_id')->unsigned();
$table->foreign('following_users_id')
->references('id')
->on('following_users');
$table->bigInteger('user_id')->unsigned();
$table->timestamps();
});
}

我已经完成了FollowController但是当尝试检查用户是否已被关注时,问题就来了。

在模型中跟踪关系User

public function followingUserList()
{
return $this->hasOne('AppFollowingUser');
}
/**
* Get the stories associated with the user through an intermediate table
*
*/
public function followingUsers()
{
return $this->hasManyThrough(
'AppFollowingUserItem',
'AppFollowingUser',
null,
'following_users_id'
);
}

FollowingUserUserFollowingUserItem的模型关系

public function user()
{
return $this->belongsTo('AppUser');
}

public function users()
{
return $this->hasMany('AppFollowingUserItem','following_users_id');
}

这是我FollowController

class FollowController extends Controller
{
//
public function index($id)
{
$user = User::find($id);
$logged_userId = Auth::User();
if ($user->id == $logged_userId->id) {
return [
'status' => false,
'message' => 'You can not Follow yourself',
];
}
if ($user && $logged_userId) {
$checkUsers = FollowingUser::where('user_id', $user->id)->get()->users()->where('user_id', $logged_userId->id);
if ($checkUsers) 
{
return 'already followed';
}
else 
{
$user->followingUserList()->save(new FollowingUser())->users()->save(new FollowingUserItem(['user_id' => $logged_userId->id]));
return 'sucess';
}
}
}       
}

我去错误方法 Illuminate\Database\Eloquent\Collection::users 不存在。

当你调用get()Laravel时会返回一个collection,因为它不知道那里会有多少行。这就是为什么你得到collection没有用户设置错误的原因。由于您过滤了一个 id,因此您知道只有一个,因此您可以使用first()方法。

因此,更改代码以使用first()

$checkUsers = FollowingUser::where('user_id', $user->id)->first()->users()->where('user_id', $logged_userId->id);

最新更新