【问题标题】:Get records from a table where an array of deleted_organization_id does not contain organization id using eloquent laravel 5.6使用 eloquent laravel 5.6 从已删除组织 ID 数组不包含组织 ID 的表中获取记录
【发布时间】:2018-12-23 00:22:10
【问题描述】:

我有一个表“帖子”,它通常有诸如“id、标题、内容、...、deleted_for_organization”之类的列

其他表:带有id、名称、描述的组织

用户:id,name,email,password,organization_id

目前,我将组织 ID 以 json 数组格式(例如 [1,2,3])存储在 deleted_for_organization 列中。这是指该帖子已针对该组织删除,并且不应对组织的任何成员可见。

现在,每当请求加载所有帖子时,我只想使用 eloquent 为其组织删除那些未删除的帖子。

这可能吗,还是我需要创建另一个数据透视表来维护多对多的关系。

在浏览 laravel 雄辩的文档时,我遇到了

$posts = App\Post::whereDoesntHave('comments', function ($query) { $query->where('content', 'like', 'foo%'); })->get();

但是,我不知道这是否适合我的问题。

【问题讨论】:

  • 虽然我不推荐使用这种结构,但 laravel 5.6 有 whereJsonContainwhereJsonDoesntContain 你可以看看。 App\Post::whereJsonDoesntContain('deleted_for_organization', $orgId)->get()
  • @rkj 你能把whereJsonContain的文档链接提供给我
  • JsonNotContains 的地方。在这里github.com/laravel/framework/blob/…

标签: laravel eloquent


【解决方案1】:

这就是你要找的。​​p>

$posts = Post::whereRaw("not json_contains(deleted_for_organization , '[".Auth::user()->organization_id."]') OR deleted_by_org is NULL")->get();

【讨论】:

    【解决方案2】:

    使用此代码检索所有尚未删除的帖子。然后将 $undeletedPosts 传递给您的刀片视图文件,然后 foreach() 循环通过它们来操作您想要的数据。这应该有效,让我知道它是否适合您。

    $userID = 10; //dynamically get user's ID instead of hard coding it
    $organizationID = $user->where('id', $userID)->first()->organization_id;
    $deletedPosts = $posts->select('id')->where('deleted_for_organization', $organizationID)->toArray();
    
    $undeletedPosts = $posts->whereNotIn('deleted_for_organization', $deletedPosts)->get();
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2022-11-04
      • 1970-01-01
      • 2012-03-18
      • 2019-07-14
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多