0

So, I have a pivot table called user_filmscores, where the users can ''follow (watching, dropped, hold-on...)'' a film and add a rating on it.

In the userController I have this function:

    public function userFilm(Request $request){
        $data = $request->all();
        $validator=Validator::make($data,[
            'user_id' => 'required',
            'film_id' => 'required',
            'state' => 'required',
            'score' => 'nullable'
        ]); 
        if($validator->fails()){
            return response()->json([
                'ok' => false,
                'error' => $validator->messages(),
            ]);
        }
        $film = Film::find($data['film_id']);
        $user = User::find($data['user_id']);
        $filmId=$data['film_id'];
        $userId=$data['user_id'];
//Check if the relationship exists (I tried many methods but always the same result with false)
        /*$hasFilm = User::where('id', $data['user_id'])->whereHas('film', function ($q) use ($filmId) {
            $q->where('id', $filmId);
        })->exists();*/
        $hasFilm = $user->film()->where('film_id', '=', $filmId)->exists();
        /*$user->film()->sync($film->getKey(), [
            'film_id' => $data['film_id'],
            'user_id' => $data['user_id'],
            'state' => $data['state'],
            'score'=> $data['score']
        ]);*/
        if(User::where('id', $userId)->where('id')){
            $user->film()->attach($film->getKey(), [
                'film_id' => $data['film_id'],
                'user_id' => $data['user_id'],
                'state' => $data['state'],
                'score'=> $data['score']
            ]);
        }else{
            $user->film()->detach($film->getKey());
        }
        
    }

In the final part of the code, I want to check if the relationship between the user and the film exists, to make an action or another. But when I try to check if the relationship exists, it always returns me a false. I thought to do it like, if there is a relationship, first delete the old relationship, and then create a new one. I don't know if there is a better way to do it.

User model has this function:

public function film(){
        return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'user_id', 'film_id', 'state', 'score');
}

Film model has this function:

public function user(){
        return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'film_id', 'user_id', 'state', 'score');
}

Users table: Users table

Films table: Films table

User_filmscores table: User_filmscores table

Caesar
  • 25
  • 3
  • Does this answer your question? [Laravel save / update many to many relationship](https://stackoverflow.com/questions/24702640/laravel-save-update-many-to-many-relationship) – Haridarshan Jun 17 '21 at 13:25
  • @Haridarshan I tried to only use sync, but it returns me this error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `user_filmscores` (`film_id`, `user_id`) values (1, ?)) – Caesar Jun 17 '21 at 13:34
  • @Haridarshan I use the sync like this: $user->film()->sync($film->getKey(), [ 'film_id' => $data['film_id'], 'user_id' => $data['user_id'], 'state' => $data['state'], 'score'=> $data['score'] ]); – Caesar Jun 17 '21 at 13:35
  • check `user_id` is being passed to it or not. Also, enable query debug log to check what exact query is being executed by the ORM just for debugging purpose. – Haridarshan Jun 17 '21 at 13:36
  • `sync` takes two parameters, `public function sync($ids, $detaching = true)` where second is boolean value but you're passing an array to it. You'll need to change the way you're calling `sync`. This might help https://stackoverflow.com/a/37583796/2324206 – Haridarshan Jun 17 '21 at 13:46
  • @Haridarshan but I want to update the attributes "score" and "state", how I could do that? – Caesar Jun 17 '21 at 15:53
  • If you'll refer the last link which I've shared or this one https://stackoverflow.com/a/28903837/2324206, it shows how we can sync additional pivot fields – Haridarshan Jun 17 '21 at 17:38

0 Answers0