【问题标题】:Laravel : How to get all the rows from a table except the first one?Laravel:如何从表中获取除第一行之外的所有行?
【发布时间】:2021-09-14 06:00:31
【问题描述】:

我想选择“用户”表中的所有用户,但第一个用户除外,因为它是管理员, 我在我的控制器中使用这个函数索引,但它不起作用。

public function index()
{
    // this '!=' for handling the 1 row 
   $user = User::where('id', '!=', auth()->id())->get();
    
    return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    这里最好用whereNotIn方法

    注意:首先你找到管理员角色用户并创建一个静态数组

    $exceptThisUserIds = [1];
    $user = User::whereNotIn('id', $exceptThisUserIds)->get();
    

    【讨论】:

      【解决方案2】:

      仅使用id 指定管理员用户不是一个好主意。更好的设计是使用像is_admin 这样的标志作为用户模型的属性。 您仍然可以使用以下代码获取id 大于1 的用户:

      User::where('id', '>', 1)->get()
      

      【讨论】:

        【解决方案3】:

        为了让数据跳过第一个,你应该使用 skip() 方法并按照下面的代码进行操作

        public function index()
        {
           $user = User::orderBy('id','asc')->skip(1)->get();
            
            return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
        }
        

        【讨论】:

        • 我使用了你的脚本,但是我得到了这个错误:SQLSTATE[42000]: Syntax error or access violation: 1064 你的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的“偏移 2”附近使用正确的语法(SQL:select * from users where id != 2 offset 2)
        • 这不是跳过的工作方式。你必须使用skiptake
        • @imane 像这样的东西:User::skip(1)->take(4)->get();。它会给你从第二个开始的前 4 个用户(跳过第一个)
        • @farzin 我的管理员 id 是 2 但我只需要 id=2 之后的所有行,我需要给出一个确切的数字吗?
        • @imane 如果您的管理员 ID 为 2,您可以这样做:User::where('id', '>', 2)->get()
        猜你喜欢
        • 2011-01-16
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        • 2017-09-08
        • 2011-01-24
        • 2010-09-23
        相关资源
        最近更新 更多