如何使用内部连接选择?

时间:2016-07-24 07:50:15

标签: php laravel eloquent laravel-5.2

我正在尝试使用查询生成器执行 INNER JOIN 。但是当我试图在我的表中检索这一切时,它说错过了参数2.

  

缺少Illuminate \ Database \ Query \ Builder :: join()的参数2,在第63行的C:\ Users \ JohnFrancis \ LaravelFrancis \ app \ Http \ Controllers \ DocumentController.php中调用并定义

我不知道我的ALIAS是否错误,但我只是基于我的SQL查询。见下文。

SQL

SELECT D.title, C.category_type, U.username, DU.dateReceived FROM document_user DU
#1st JOIN
INNER JOIN users U ON DU.sender_id = U.id
#2nd JOIN
INNER JOIN documents D ON DU.document_id = D.id
#3rd JOIN
INNER JOIN categories C ON C.id = D.category_id;

结果

Result

数据库图表

SC

控制器

public function showDocuments()
{

    $documentsList = DB::table('document_user')
        ->select('D.title', 'C.category_type', 'U.username', 'DU.dateReceived')
        ->join('users AS U')->on('DU.sender_id', '=', 'U.id')
        ->join('documents AS D')->on('DU.document_id', '=', 'D.id')
        ->join('categories AS C')->on('C.id', '=', 'D.category_id')
        ->where('sender_id', '!=', Auth::id()->get());

    return view ('document.show')->with('documentsList', $documentsList);
}

我想为当前用户检索 EXCEPT 。正如您在此处所见,我添加了 where 子句。 ->where('sender_id', '!=', Auth::id()->get());

查看

<table class = "table">

        <thead>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Sender</th>
                <th>Date Received</th>
                <th>Action</th>
            </tr>               
        </thead>

        <tbody>
        @foreach ($documentsList as $list)
            <tr class = "info">
            <td>{{ $list->title }}</td>
            <td>{{ $list->category_type }}</td>
            <td>{{ $list->username }}</td>
            <td>{{ $list->dateReceived }}</td>
            <td><a href = "#"><button type = "submit" class = "btn btn-info">Read</button></a></td>
            </tr>
        @endforeach
        </tbody>

</table>

1 个答案:

答案 0 :(得分:0)

阅读了很多博客后,我发现这些课程很有用。

http://jpcamara.com/selecting-carefully-laravel-joins/

$documentsList = DB::table('document_user')->select('documents.title', 'categories.category_type', 'users.username', 'document_user.dateReceived')
        ->join('users', 'users.id', '=', 'document_user.sender_id')
        ->join('documents', 'documents.id', '=', 'document_user.document_id')
        ->join('categories', 'categories.id', '=', 'documents.category_id')
        ->where('sender_id', '!=', Auth::id())->get();