【问题标题】:paginate merged collections (or: how to sort by presence of a string)对合并的集合进行分页(或:如何按字符串的存在进行排序)
【发布时间】:2016-12-01 03:06:35
【问题描述】:

我最初有这个搜索词的解决方案:

Post::where('title', 'LIKE', '%'.$searched.'%')->orWhere('content', 'LIKE', '%'.$searched.'%')->paginate(100);

我想要什么:

我希望标题中包含术语的记录位于集合的顶部

我的临时解决方案:

很明显:

$posts1 = Post::where('title', 'LIKE', '%'.$searched.'%')->paginate(100);
$posts2 = Post::where('content', 'LIKE', '%'.$searched.'%')->paginate(100);

$object = $posts1->merge($posts2);

要解决的问题

$object 集合无法分页。我收到错误Method hasPages does not exist.。 有什么方法可以将分页功能保留在结果(排序和合并)集合上?

【问题讨论】:

  • 为什么不改用union?只需联合这 2 个选择查询 gyazo.com/a94c16f4e8683c7d0def54cde18c5899
  • 同样的错误:Method hasPages does not exist.
  • 您使用union时出现错误?
  • 不,抱歉,贴错了。使用您的解决方案时,我得到SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from posts` where content LIKE %konf%) union (select * from posts where title LIKE %konf%))`
  • 你能截屏(显示)你更新的代码吗?同样,当您联合查询时,它必须指定相同数量的列

标签: php laravel collections eloquent laravel-5.3


【解决方案1】:

为什么不使用

->orderByRaw()

他们使用

'(case when title LIKE "%'.$searched.'%" then 1 else 2 end) ASC'

因此,名字中包含$searched 的人会排在最前面

所以你的查询构建器会是这样的

Post::where('title', 'LIKE', '%'.$searched.'%')
->orWhere('content', 'LIKE', '%'.$searched.'%')
->orderByRaw('(case when title LIKE "%'.$searched.'%" then 1 else 2 end) ASC')
->paginate(100);

【讨论】:

  • 您的答案似乎很有希望,但我不知道如何修复语法。如果我使用你的代码,我会得到Column not found: 1054 Unknown column '(when name LIKE "%konf%" then 1 else 2)' in 'order clause'
  • 这给了我语法错误:->orderByRaw("CASE WHEN title LIKE %konf% THEN 1 else 2 END ASC") 任何提示? (注意:我硬写了搜索词以简化调试。)错误说:Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax...
  • @Peter ops 我忘了在 orderByRaw 的开头添加“case”。并在末尾添加“end”
  • 我自己更正了。我仍然有语法错误。我不知道出了什么问题。
  • @Peter 有什么错误?我测试了这个查询生成器,它没有产生任何错误
猜你喜欢
  • 2015-09-18
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多