php - 调用数组 laravel 上的成员函数 where()

标签 php mysql laravel join controller

我有两个表tbl_law_master & tbl_law_sub_master 在这两个表上都有一个名为 assigned_to 的列,该列存储用户的 ID。

我的任务是通过加入 tbl_law_master 的 law_id 从 tbl_law_sub_master 获取特定 user's idsublaw

这是我的代码,

$law_id = $_GET['law_id'];

$sublaw = DB::table('tbl_law_sub_master')
            ->select('tbl_law_sub_master.*', 'tbl_law_master.lm_id', 'tbl_law_master.law_name', 'tbl_law_master.id as lawId')
            ->leftJoin('tbl_law_master', 'tbl_law_master.id', '=', 'tbl_law_sub_master.lm_id')
            ->where('tbl_law_sub_master.lm_id', $law_id)
            ->orderBy('type_of_event', 'asc')
            ->orderBy('section', 'asc')
            ->orderBy('rules', 'asc')
            ->orderBy('notification', 'asc')
            ->orderBy('circular', 'asc')->get();

if (!in_array(Auth::user()->role, [1, 7])) 
{
   $sublaw = $sublaw->where('tbl_law_master.assigned_to', Auth::user()->id);
}

它显示错误

Call to a member function where() on array

最佳答案

问题是您已经调用了查询的 get(),然后再次调用了 where()

你应该像这样使用where子句函数

$sublaw = DB::table('tbl_law_sub_master')
        ->select('tbl_law_sub_master.*', 'tbl_law_master.lm_id', 'tbl_law_master.law_name', 'tbl_law_master.id as lawId')
        ->leftJoin('tbl_law_master', 'tbl_law_master.id', '=', 'tbl_law_sub_master.lm_id')
        ->where(function($query) use ($law_id) {
            $query->where('tbl_law_sub_master.lm_id', $law_id);
            if (!in_array(Auth::user()->role, [1, 7])) 
            {
                $query->where('tbl_law_master.assigned_to', Auth::user()->id);
            }
        })
        ->orderBy('type_of_event', 'asc')
        ->orderBy('section', 'asc')
        ->orderBy('rules', 'asc')
        ->orderBy('notification', 'asc')
        ->orderBy('circular', 'asc')->get();

关于php - 调用数组 laravel 上的成员函数 where(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335477/

相关文章:

包含页面中的 PHP die() 而不会从主页中消失

php - 我使用ReCaptcha v3出现 "timeout-or-duplicate"错误

mysql - rails 4 : Need help understanding how to create a form for a joining table

php - 如果列有 2 个相同的记录,则选择最新记录

php - Laravel Passport JWT 身份验证失败

php - 在 Laravel 中使用 SQL 查询数组获取 html 图像源

php - 使用 php 从 shell 启动 sudo

php - 在 IMG URL 中显示下拉选择名称

php - 在 Codeigniter 中获取额外空间(如查询)

php - Laravel - 多公司范围