Check if row exists, Laravel

后端 未结 4 1070
失恋的感觉
失恋的感觉 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: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
    

提交回复
热议问题