【问题标题】:Laravel Eloquent with conditionLaravel Eloquent 有条件
【发布时间】:2022-07-06 04:40:56
【问题描述】:

谁能帮帮我?

我有这样的口才

$data = DocumentFile::with(['document_folder', 'document_request.user.profile'])
        ->where('isactive', true)
        ->when($request->search, function($query, $search) {
                $query->where('name', 'ilike', '%'.$search.'%');
        })
        ->orderBy('updated_at', 'DESC')
        ->paginate($paginate)

但它没有显示我想要的数据。


我有 3 个这样的模型:

  • DocumentFolder,字段:id、名称
  • DocumentFile,字段:id、name、is_private、is_active、created_by、updated_at、document_folder_id
  • DocumentRequest,字段:id、user_id、document_file_id

1 DocumentFolder有很多DocumentFile1 DocumentFile有很多DocumentRequest


我想显示有条件的数据:

  1. 如果DocumentFile 是_active = true,显示它,如果is _active = false
  2. 如果 DocumentFile is_private = false 显示它
  3. 如果 DocumentFile is_private = true,必须检查 DocumentRequest 来自身份验证登录的用户 ID 在 DocumentRequest,如果是,请显示,如果不是,则不要
  4. 如果用户登录在 created_by 上从 DocumentFileuser_id,如果是则显示它
  5. 可以通过DocumentFile 名称搜索数据
  6. updated_at => DESCDocumentFile 排序的数据
  7. 分页文档文件

【问题讨论】:

    标签: laravel if-statement eloquent conditional-statements switch-statement


    【解决方案1】:

    首先,您必须在模型中定义所有关系('document_folder'、'document_request.user.profile')才能使用“with() 查询加载关系” 然后试试这个:

    $data = DocumentFile::with(['document_folder', 'document_request.user.profile'])
        ->where('is_active', true)
        ->where('name', 'like', '%'.$request->search.'%')
        ->orderBy('updated_at', 'DESC')
        ->paginate($paginate);
    

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 2020-08-15
      • 2014-11-15
      • 2015-05-17
      • 1970-01-01
      相关资源
      最近更新 更多