首页 > 解决方案 > 如何在 Laravel QueryBuilder 中基于 json 列加入

问题描述

帖子表

    |id|值|
    |1 |霍格 |
    |2 |风雅 |
    |3 |piyo |

some_posts 表

    |id|post_ids|
    |1 |[1, 2] |
    |2 |[1] |
    |3 |[1,2,3]|

我想使用QueryBuilder加入。我应该怎么办?

那是不可能的。

DB::table('some_posts')
  ->join('posts', 'some_posts.post_ids', 'posts.id');

SQLSTATE [42883]:未定义函数:7 错误:运算符不存在:json = integer\n LINE 1: ...ts" 在 "some_posts" 上内连接 "posts"。"post_ids" = "posts".... \n

提示:没有运算符与给定的名称和参数类型匹配。您可能需要添加显式类型转换。(SQL: select "some_posts".* from "some_posts" 内部连接 ​​"posts" on "some_posts"."post_ids" = "posts"."id" where "some_posts"."some_id" = 384)

谢谢,

标签: phplaravel

解决方案


Post您可以在模型中使用集合

Post.php

Class Post extends model

public function somePosts()
{
  return $this->belongsTo('some_posts`, 'post_ids');
}

然后,改变这个

DB::table('some_posts')
->join('posts', 'some_posts.post_ids', 'posts.id');

Post::with('somePosts')->get();

推荐阅读