【问题标题】:Select $id from ids field containg $id1,$id2,$id3从包含 $id1,$id2,$id3 的 ids 字段中选择 $id
【发布时间】:2021-05-11 18:26:18
【问题描述】:

我在 Laravel 中的模型有一个如下所示的 linked_ids 字符串字段:
echo $model->linked_ids
1,2,3,4,5
我想进行一个查询,让我在linked_ids 中获取所有具有给定ID 的记录。
目前我有:
Model::where('linked_ids', 'LIKE', '%' . $model->id . '%');
但这比我想要的更多(如果例如:$model->id 是 3 => 选择:1,32,67)\

由于我不知道 id 的位置也不知道 id 的顺序,我该如何避免这种情况?我想在 eloquent 中做到这一点,但也可以使用 DB::raw() 之类的东西来运行 sql 查询。

【问题讨论】:

  • Model::whereIn('linked_ids', [1,2,3,4,5]); 应该这样做
  • 所以linked_ids 是一个包含ID 列表的varchar?这是一种糟糕的数据方法,您应该考虑将其规范化为适当的关系表
  • @krisgjika 你可以在 Laravel 中与同一模型建立关系:here is a valid example of a one to many relationship on the same model
  • 我从来没有说过我因为数据的状态而责怪你;我以前采用过这种形式的代码,但就像我说的,考虑改变它。此外,您可以在同一张表之间进行数据透视; model_linksmodle_a_idmodel_b_id6, 16, 26, 3 等。这样的 CSV 列查询起来非常困难且效率低下,正如您发现的那样当你想要 3 时检索 ID 32
  • 听起来不错!我想了更多,您可以有点使用您的数据结构进行这项工作。假设您有模型 id: 6,链接 ID 为 '1,2',此查询应该有效:Model::whereIn('id', explode(',', Model::find(6)->linked_ids'))->get();;您必须从数据库中获取记录,分解linked_ids 并查询id。但重点仍然在于您无法有效地查询linked_ids

标签: sql laravel eloquent


【解决方案1】:

保留您的 id 的方法很糟糕,但如果您真的无法更改它,您可以利用 LazyCollections 并使用 php 进行过滤。

我确信有一种方法可以直接在 MySQL(或您正在使用的任何 dbms)中执行此操作,但这就是我所拥有的。

$id = 3;
Model::cursor()
    ->filter(function ($model) use ($id) {
        return in_array($id, explode(',',  $model->linked_ids));
    })
    // then chain one of these methods
    ->first();    // returns the first match or null
    ->collect();  // returns an Illuminate\Support\Collection of the results after the filtering
    ->all();      // returns an array of Models after the filtering
    ->toArray();  // returns an array and transforms the models to arrays as well.
    ->toJson();   // returns a json string

请注意,这将仍然执行 SELECT * FROM table 而不进行任何过滤(除非您在 cursor() 之前链接一些 where 方法,但它不会将任何模型加载到内存中(通常是Laravel 中大查询的瓶颈)

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 2019-06-09
    • 2019-06-19
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多