调用未定义的方法 IlluminateDatabaseEloquentCollection::save()


Call to undefined method IlluminateDatabaseEloquentCollection::save() laravel

我做了一个函数,让我想到了错误:

Call to undefined method Illuminate'Database'Eloquent'Collection::save()

我不明白它为什么要扔

public function multiplelinkPlayerWithFamily($parent_id)
{
    $player_id = Input::get('player_id');
    $CheckRelationship = UsersRelationship::where('parent_user_id', $parent_id)->where('child_user_id', $player_id)->first();
    if($CheckRelationship) {
        return Response::json( [
            'ok'=> false,
            'message'=> 'The profiles are currently linked '
        ] ,422);
    }
    $user = User::find($player_id);
    $user->parent_id = $parent_id;
    $user->updated_by = $parent_id;
    $user->save();
    $UsersRelationship = new UsersRelationship;
    $UsersRelationship->parent_user_id = $parent_id;
    $UsersRelationship->child_user_id = $player_id;
    $UsersRelationship->save();
    $udata = ApiUserController::getLoginUserData();
    return Response::json([
        'ok'=> true,
        'message'=> 'Linked',
        'udata'=> $udata
    ] ,200);
}

我看不出你的模型是如何构建的,但看起来你实际上已经把一个模型变成了一个关系:即。 $UsersRelationship看起来您正在尝试在用户之间建立多对多关系,对吗?

public function parents()
{
    return $this->belongsToMany('User','users_relationships','child_id','parent_id');
}
 public function children()
 {
    return $this->belongsToMany('User','users_relationships','parent_id','child_id');
 }

正确设置关系后,您可以致电:

$user->parents()->attach($parent_id);

Eloquent 通过 get 方法或关系返回的所有多结果集都将返回一个集合对象。如果查询结果可能返回多个值,则 Laravel 将返回一个集合。了解返回集合的查询方法将省去在集合上调用 Eloquent 模型方法的问题。

查询最有可能从数据库中返回

多条记录,或者从数据库中返回任何记录。这将导致"Eloquent"返回集合,即使找到的记录数为 1。由于返回值是一个集合,因此我们需要遍历返回的集合才能访问单个模型。

因此,请尝试替换以下代码:

$user = User::find($player_id);
$user->parent_id = $parent_id;
$user->updated_by = $parent_id;
$user->save();

并按如下所示替换它:

$user = User::find($player_id);
$user->each(function($user)
{
    $user->parent_id = $parent_id;
    $user->updated_by = $parent_id;
    $user->save();
});

希望它能奏效。