【问题标题】:Convert PHP SQL into Laravel query builder [duplicate]将 PHP SQL 转换为 Laravel 查询构建器 [重复]
【发布时间】:2021-09-01 01:42:14
【问题描述】:

我是 Laravel 新手,使用 SQL 2 年了,但是不明白在使用复杂 SQL 时如何完全迁移到 Laravel 的查询。 我如何将以下 SQL 字符串放入 Laravel 的查询生成器中,谢谢。

$sqlQuery = "SELECT topic_id, topic_subject, cat_name, user_name, topic_date FROM topics, categories, users WHERE topic_by = user_id AND topic_cat = cat_id AND topic_cat = '$topicCat' ORDER BY topic_date DESC limit 10";

【问题讨论】:

标签: php sql laravel


【解决方案1】:
$sqlQuery = "SELECT topic_id, topic_subject, cat_name, user_name, topic_date 
             FROM topics, categories, users WHERE topic_by = user_id AND  
             topic_cat = cat_id AND topic_cat = '$topicCat'
             ORDER BY topic_date DESC limit 10";

在提问之前,您需要做一些研究 不用担心我会解释的

DB::table('users')
->join('categories','users.id', '=', 'categories.user_id')
->join('topics','users.id', '=', 'topics.user_id ')
->where('topics.topic_by','users.id')
->where('topics.topic_cat','categories.id')
->where('topics.topic_cat', $topicCat)
->orderByRaw('topics.topic_date - created_at DESC')
->limit(10)
->get();

这看起来像带有类别和类别的用户表映射是带有主题的映射,因为我不知道数据库结构您可以像这样连接多个表,还可以根据您的要求添加条件。

【讨论】:

    【解决方案2】:

    如果您创建模型并添加到文件的顶部,您可以通过创建模型使其更简单。users::select('enter the value you want need in table here')->join('categories','users.id', '=', 'categories.user_id')->join('topics','users.id', '=', 'topics.user_id ')->where('topics.topic_by','users.id')->where('topics.topic_cat','categories.id')->where('topics.topic_cat', $topicCat)->orderByRaw('topics.topic_date - created_at DESC')->limit(10)->get();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2020-10-19
      • 2016-02-11
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多