【问题标题】:Laravel pluck and findOrFail not returning correct rowLaravel 采摘和 findOrFail 没有返回正确的行
【发布时间】:2017-01-03 02:37:12
【问题描述】:

我正在使用Gate 外观来检查用户是否可以删除一行。

 Gate::define('delete-cons', function ($user, $cons) {
        $c_id = Cons::findOrFail($cons)->pluck('c_id');
        return $user->c->id == $c_id;
    });

如果我输出$cons,它会返回4

4   2   1   Mr  Joe Bloggs  male    1234567 0   1_1474822931.png    2017-01-02 17:33:49 2017-01-02 17:33:49 NULL

上面的第一列是主键,所以我们可以看到,它应该返回这一行。

但是,在查询后输出$c_id时,它显示:

#items: array:4 [▼
    0 => 1
    1 => 1
    2 => 1
    3 => 2
  ]

我原以为它会返回 2 的最后一个结果,但它会返回表中的所有 4 行!

即使我手动输入要获取的行的 ID:

$c_id = Cons::findOrFail(4)->pluck('c_id');

它仍然返回所有行。

我知道我可以使用

$c_id = Cons::where('id', $cons)->pluck('c_id');

哪个工作正常,但我遵循 Laravel Gate 示例,其中 FindOrFail 引发异常。

非常感谢。

【问题讨论】:

    标签: php laravel laravel-5.3


    【解决方案1】:

    您不应该在findOrFail() 之后使用pluck(),因为它只会运行查询以从所有行中获取c_id。改为这样做:

    $c_id = Cons::findOrFail($cons)->c_id;
    

    如果出于某种原因您想使用pluck(),请执行以下操作:

    $c_id = Cons::where('column', $cons)->pluck('c_id');
    

    【讨论】:

    • 完美运行,感谢您的解释!我可以在 8 分钟内接受答案。
    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2020-04-16
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2021-06-10
    相关资源
    最近更新 更多