【问题标题】:How to create a query in laravel which fetch post and its user detail如何在 laravel 中创建一个获取帖子及其用户详细信息的查询
【发布时间】:2017-09-07 20:37:28
【问题描述】:

我正在尝试获取用户发布并在帖子下方显示他们的用户名和 ID 我如何创建这样的查询

这是我的帖子表

  ---------------------------------------------------------------------
  | id | user_id | title   | content   | status | time                |
  | 1  |   2     | example | Something | active | 2017-07-11 13:48:26 |
  | 2  |   2     | example | Something | active | 2017-07-11 13:48:26 |
  | 3  |   3     | example | Something | active | 2017-07-11 13:48:26 |
  | 4  |   4     | example | Something | active | 2017-07-11 13:48:26 |
  | 5  |   5     | example | Something | active | 2017-07-11 13:48:26 |
  ---------------------------------------------------------------------

用户表

  ------------------------------------------------------------
  | id |  name   |password |    img    | last_login          |
  | 1  |  User1  | example | Something | 2017-07-11 13:48:26 |
  | 2  |  User2  | example | Something | 2017-07-11 13:48:26 |
  | 3  |  User3  | example | Something | 2017-07-11 13:48:26 |
  | 4  |  User4  | example | Something | 2017-07-11 13:48:26 |
  | 5  |  User5  | example | Something | 2017-07-11 13:48:26 |
  ------------------------------------------------------------

现在我想从数据库中获取所有帖子并从用户表中获取 - 名称、img、用户名等...

这是我的查询到现在的样子

$p1 = App\Models\Post::where('status', 'active')
            ->orderBy('id', 'desc')
            ->take(6)
            ->get();

【问题讨论】:

  • 在您的模型中添加relationship 并执行Post::with("user")->where...

标签: php mysql laravel laravel-5


【解决方案1】:

试试这个……我只使用了 JOIN,因为每个帖子都有一个用户…… 你可以参考这个链接https://laravel.com/docs/5.4/queries#joins

DB::table('post')
    ->select('post.*','user.id','user.name')
    ->join('user','user.id','=','post.user_id')
    ->get();

试试这个你需要选择的类别,只需将它添加到选择子句中......

DB::table('post')
    ->select('post.*','user.id','user.name', 'category.*')
    ->join('user','user.id','=','post.user_id')
    ->join('category','post.id','=','category.post_id')
    ->get();

【讨论】:

  • 还有什么方法可以获取类别吗?有一个具有 id 和 post_id 的类别表。
【解决方案2】:

通过使用 laravel 查询生成器

这样试试

$result = DB::table('users')
    ->leftJoin('post', function ($join) {
        $join->on('users.id', '=', 'post.user_id');
    })
    ->orderBy('users.id', 'desc')
    ->get();

【讨论】:

    猜你喜欢
    • 2018-09-20
    • 2020-05-06
    • 2020-12-23
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多