Check if row exists, Laravel

后端 未结 4 1071
失恋的感觉
失恋的感觉 2021-02-04 02:13

I have the following db structure:

items:
id, name, user_id

users table:
id, name

user_favorites table:
id, user_id, item_id

On my items perm

相关标签:
4条回答
  • 2021-02-04 02:46

    You may want something like this:

    $user_favorites = DB::table('user_favorites')
        ->where('user_id', '=', Auth::user()->id)
        ->where('item_id', '=', $item->id)
        ->first();
    
    if (is_null($user_favorites)) {
        // It does not exist - add to favorites button will show
    } else {
        // It exists - remove from favorites button will show
    }
    
    0 讨论(0)
  • 2021-02-04 02:48

    Let User_favorite be a model that accesses your user_favorites table

    $result = User_favorite::where('user_id',Auth::getUser()->id)
                             ->where('item_id',$item->id)
                             ->first();
    
    if (is_null($result)) {
    // Not favorited - add new
        User_favorite::create(['user_id'=>Auth::getUser()->id,'item_id'=>$item->id]);
    } else {
    // Already favorited - delete the existing
        $result->delete();
    }
    
    0 讨论(0)
  • 2021-02-04 02:48

    The simplest way to do is to use toggle() method of many-to-many relationship.

    e.g.

    $user->roles()->toggle([1, 2, 3]);
    

    The many-to-many relationship also provides a toggle method which "toggles" the attachment status of the given IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached

    It also returns an array which tells you if the ID is attached or detached in DB.

    0 讨论(0)
  • 2021-02-04 02:54

    I advise you to use exists() or count() to check, not use first().

    The fastest way:

    $result = DB::table('user_favorites')
        ->where('user_id', '=', Auth::user()->id)
        ->where('item_id', '=', $item->id)
        ->exists();
    

    Or:

    $result = DB::table('user_favorites')
        ->where('user_id', '=', Auth::user()->id)
        ->where('item_id', '=', $item->id)
        ->count();
    

    SQL:

    select count(*) as aggregate from `user_favorites` where *** limit 1
    

    The faster way: only select id

    $result = DB::table('user_favorites')
        ->where('user_id', '=', Auth::user()->id)
        ->where('item_id', '=', $item->id)
        ->first(['id']);
    

    SQL:

    select id from `user_favorites` where *** limit 1
    

    The normal way:

    $result = DB::table('user_favorites')
        ->where('user_id', '=', Auth::user()->id)
        ->where('item_id', '=', $item->id)
        ->first();
    

    SQL:

    select * from `user_favorites` where *** limit 1
    
    0 讨论(0)
提交回复
热议问题