【问题标题】:get referral users against user id in laravel query在 laravel 查询中根据用户 ID 获取推荐用户
【发布时间】:2023-04-07 11:46:01
【问题描述】:

我需要获取一个用户推荐的用户以及第一个用户的推荐用户推荐的所有其他用户。

为了得到这种结果,我在mysql中递归查询,我可以得到确切的结果,查询是:

        WITH recursive cte as ( 
select * from users where reff_user = '$id' 
union all 
select t.* from cte c
  join users t 
    on t.reff_user = c.id ) 
select * 
  from cte 
 ORDER 
    BY created_at DESC
        

我想知道如何使用 laravel 查询获得相同的结果。

我尝试了用户模式中的 belongsTo 和 hasMany 函数来获取推荐用户,但结果为空,而使用递归查询,我可以将所有用户归结为特定用户。

请举例说明如何在 laravel 中使用递归查询。

--------------发布编辑--------

我也尝试过原始查询:

DB::select( DB::raw("WITH recursive cte as (select * from users where reff_user = '$id' union all select t.* from cte c join users t on t.reff_user = c.id) select * from cte ORDER BY created_at DESC") );

但出现此错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recursive cte as (select * from users where reff_user = 1 union all select t.* f' at line 1 (SQL: WITH recursive cte as (select * from users where reff_user = 1 union all select t.* from cte c join users t on t.reff_user = c.id) select * from cte ORDER BY created_at DESC)

【问题讨论】:

  • 注意:对所有数据使用占位符值,比如这里的$id,它没有在查询中注入位置。
  • @tadman 感谢兄弟的评论,你能举个占位符值的例子吗?我会非常感谢你。
  • 如果你真的卡住了,你可以在 Laravel 中使用raw queries with placeholders using DB::raw。虽然最好尝试用 Eloquent 来表达这一点,但这并不总是可行的,也不值得大惊小怪。
  • 我已经尝试使用原始查询,但收到此错误。虽然它适用于简单的 php 查询。错误是: SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在第 1 行使用“recursive cte as (select * from users where reff_user = 1 union all select t.* f' (SQL: WITH recursive cte as (select * from users where reff_user = 1 union all select t.* from cte c join users t on t.reff_user = c.id) select * from cte ORDER BY created_at DESC)
  • 我明白了,好吧,让我们等一下 laravel 专家开发人员 :) 。直到我自己挣扎

标签: php mysql laravel eloquent


【解决方案1】:

我对此进行了很多搜索,之后我通过将网站上传到另一个主机进行了一些实践,然后我从 cpanel 升级了 mysql 版本,然后检查了网站,查询工作正常。

So the issue was mysql version mismatch as @tadman said in the comment section. Thanks to him.

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2016-09-29
    • 2017-12-07
    相关资源
    最近更新 更多