检查行是否存在,Laravel [英] Check if row exists, Laravel

查看:132
本文介绍了检查行是否存在,Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据库结构:

  items:
id,name,user_id

用户表:
id,名称

user_favorites表:
id,user_id,item_id

在我的项目永久链接页面上,我有一个添加到收藏夹按钮,将新行插入 user_favorites



如果用户已经拥有收藏夹,我希望能够将其替换为从收藏夹中移除。



我无法弄清楚这个背后的逻辑 - 我需要检查 user_favorites 中是否存在一行,它具有当前用户的id和永久链接项ID?这对我来说不起作用:

  if(Auth :: user() - > id){
if (!is_null(DB :: table('user_favorites') - > where('user_id','=',Auth :: user() - > id) - > where('item_id','=' $ item-> id) - > first())){
//从收藏夹中删除按钮将显示
}
}
/ pre>

解决方案

您可能想要这样:

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

if(is_null($ user_favorites)){
//它不存在 - 添加到收藏夹按钮将显示
} else {
//它存在 - 从收藏夹中删除按钮将显示
}


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 permalink pages, I have an 'Add to favorites' button which inserts a new row into user_favorites

I want to be able to replace it for a 'Remove from favorites' button if the user already has it in their favorites.

I can't figure out the logic behind this - do I need to check if a row exists in user_favorites that has the current user's id and the permalink item id? This did not work for me:

if (Auth::user()->id) {
    if (!is_null(DB::table('user_favorites')->where('user_id', '=', Auth::user()->id)->where('item_id', '=', $item->id)->first())) {
        // remove from favorites button will show
    }
}

解决方案

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
}

这篇关于检查行是否存在,Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆