我该如何用laravel雄辩地编写此查询

时间:2018-07-12 08:39:39

标签: php mysql laravel eloquent

我有表Users,部门,文件和shareFiles。 我想编写一个查询,当用户尝试向另一个用户发送文件时,共享功能应该捕获文件的标题以及发送文件的用户部门,该文件将保存在shareFiles表中。

  • 用户表:iddepartment_id
  • 文件表:idtitleuser_id
  • 部门表格:idname
  • ShareFiles表:titlefiledepartment_iduser_idsenderto

以下是我在分享功能中所做的事情

public function shareFile(Request $request)
    {

        $userfile = new UserFile();
        $userfile->sender = \Auth::user()->username;
        $userfile->to = $request->user;
        $userfile->title = File::select('title')->where(['user_id' => \Auth::user()->id])
        ->orWhere('id','=','user_id')->get();

        $userfile->department = DB::table('departments')->select('departments.name')
        ->join('users','departments.id','=','users.department_id')
        ->where(['users.id' => \Auth::user()->id])
        ->get();

        $userfile->user_id = \Auth::user()->id;
        $userfile->save();
        Session::flash('message','File successfully shared !!');
        return redirect('/hr/document');
    }

1 个答案:

答案 0 :(得分:0)

尝试此代码:-

For title selection:

$file = File::select('title')->where(['user_id' => \Auth::user()->id]) ->orWhere('id','=','user_id')->first();

For Department:

$dept = DB::table('departments')->select('departments.name') ->join('users','departments.id','=','users.department_id') ->where(['users.id' => \Auth::user()->id]) ->first();

注意:您也可以使用value()和pluck()(如果需要值数组)来代替select()。