【问题标题】:Laravel: How to get an array of existing ids from a column, where later on will use `whereIn`Laravel:如何从列中获取现有 id 的数组,稍后将使用`whereIn`
【发布时间】:2017-02-01 12:07:04
【问题描述】:

考虑以下函数:

public function index($countryCode, Request $request) {
    $invalidCountryTranslations = $countriesTranslation->whereIn('LanguageID', $arrayOfExistingIds)->get();
    return view('admin.countriesTranslations.create', compact('countryCode', 'languages', 'countriesTranslation'));
}

我正在使用上面的函数来找出哪些国家已经在表格中(所以它不会被调用到视图中)所以基本上$arrayOfExistingIds 应该包含来自LanguageID 列的现有行。

所以问题是,如何获取LanguageID 列的现有数组?

$arrayOfExistingIds = ???

【问题讨论】:

    标签: php sql laravel laravel-5


    【解决方案1】:

    使用pluck() 方法。

    pluck 方法检索给定键的所有值

    Model::pluck('id');
    

    【讨论】:

      【解决方案2】:

      正如 Alexey 告诉你的,使用 pluck() 方法,它将检索一个集合,如果你想要一个数组将它与 toArray()all() 方法连接起来,就像这样;

      Model::take(5)->pluck("id")->toArray();
      Model::take(5)->pluck("id")->all();
      

      这将为您提供所需的数组。 尽量不要使用 lists() 方法,因为它在 5.2.0 中已被弃用。

      【讨论】:

        猜你喜欢
        • 2019-02-03
        • 2020-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 2017-05-30
        • 2020-11-07
        相关资源
        最近更新 更多