如何获取laravel5中另一个表的列数据?

时间:2017-10-04 04:42:30

标签: php mysql laravel sorting

首先,我为我可怜的英语道歉。

我正在编写代码来对页面列表进行排序。 “link_for_sort”是一个用户功能。

function link_for_sort($column, $text, $params = [])
    {
        $direction = request()->input('order');
        $reverse = ($direction == 'desc') ? 'asc' : 'desc';

        if (request()->input('sort') == $column) {
            // Update passed $text var, only if it is active sort
            $text = sprintf(
                "%s %s",
                $direction == 'desc'
                    ? '<i class="fa fa-sort-alpha-desc"></i>'
                    : '<i class="fa fa-sort-alpha-asc"></i>',
                $text
            );
        }

        $queryString = http_build_query(array_merge(
            request()->except(['sort', 'order']),
            ['sort' => $column, 'order' => $reverse],
            $params
        ));

        return sprintf(
            '<a href="%s?%s">%s</a>',
            urldecode(request()->url()),
            $queryString,
            $text
        );
    }

它以“列”和“排序文本”作为参数。 并根据“文章”表中的输入排序返回网址。

ex)

link_for_sort ("view_count", "view");
       -> example.com/post?sort=view_count&order=desc

我想添加“投票”排序。

但“投票”数据列在另一个表“投票”中。 (“向上”栏)

我想从另一个表中使用这个用户函数。

ex)

link_for_sort ("up", "vote");
     -> example.com/post?sort=up&order=desc

我很感激你的建议。谢谢。

*project.php

'sorting' => [
    'view_count' => 'view',
    'created_at' => 'date',
],

'sorting_vote' => [
    'up' => 'vote',
],


*index.blade.php

<div class="btn-group sort__article">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    <i class="fa fa-sort"></i>
    {{ trans('forum.articles.sort') }}
    <span class="caret"></span>
  </button>

  <ul class="dropdown-menu" role="menu">
    // table: article, column: view_count,created_at
    @foreach(config('project.sorting') as $column => $text)
      <li {!! request()->input('sort') == $column ? 'class="active"' : '' !!}>
        {!! link_for_sort($column, $text) !!}
      </li>
    @endforeach

    // table: votes, column: up
    @foreach(config('project.sorting_vote') as $column => $text)
      <li {!! request()->input('sort') == $column ? 'class="active"' : '' !!}>
        {!! link_for_sort($column, $text) !!}
      </li>
    @endforeach
  </ul>
</div>


*Article.php

public function votes()
{
    return $this->hasMany( Vote::class );
}


MariaDB> desc articles;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id    | int(10) unsigned | NO   | MUL | NULL    |                |
| title      | varchar(191)     | NO   | MUL | NULL    |                |
| content    | text             | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
| thumbnail  | varchar(191)     | YES  |     | NULL    |                |
| view_count | int(10)          | NO   |     | 0       |                |
| popular    | int(10)          | NO   |     | 0       |                |
+------------+------------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)

MariaDB> desc votes;
+------------+------------------+------+-----+-------------------+-----------------------------+
| Field      | Type             | Null | Key | Default           | Extra                       |
+------------+------------------+------+-----+-------------------+-----------------------------+
| id         | int(10) unsigned | NO   | PRI | NULL              | auto_increment              |
| user_id    | int(10) unsigned | NO   | MUL | NULL              |                             |
| article_id | int(10) unsigned | NO   | MUL | NULL              |                             |
| up         | int(10)          | NO   |     | 0                 |                             |
| down       | tinyint(4)       | YES  |     | NULL              |                             |
| voted_at   | timestamp        | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------+------------------+------+-----+-------------------+-----------------------------+
6 rows in set (0.00 sec)

[添加] * ArticleController.php

public function index(Request $request, $slug = null)
{
    $upVoteQuery = "(select count(id) from votes where votes.article_id=articles.id and votes.up!=0) as up";
    $sortField = $request->input('sort', 'id');
    $sortDir = $request->input('order', 'ASC');
    $builder = new \App\Article;
    $builder = $builder->selectRaw("articles.*, $upVoteQuery")
                    ->orderBy($sortField, $sortDir)
                    ->get();

    dd($builder);
    $query = $slug
        ? \App\Tag::whereSlug($slug)->firstOrFail()->articles()
        : new \App\Article;

    $query = $query->orderBy(
        $request->input('sort', 'created_at'),
        $request->input('order', 'desc')
    );

    if ($keyword = request()->input('q')) {
        #dd($keyword);
        $raw = 'MATCH(title,content) AGAINST(? IN BOOLEAN MODE)';
        $query = $query->whereRaw($raw, [$this->fullTextWildcards($keyword)]);
    }
    dd($query);
    $articles = $query->latest()->paginate(32);

    return view('articles.index',compact('articles'));
}

1 个答案:

答案 0 :(得分:1)

请检查我的答案。我想这个例子可以帮助您解决问题。

function functionName(Request $request) {

    $upVoteQuery = "(select count(id) from votes where votes.article_id=articles.id and votes.up!=0) as up"
    $sortField = $request->input('sort', 'id');
    $sortDir = $request->input('order', 'ASC');
    $builder = new Article;
    $builder = $builder->selectRaw("articles.*, $upVoteQuery")
                    ->orderBy($sortField, $sortDir)
                    ->get();
}

在上面的示例中,我添加了一个查询来添加关系表votes计数并添加到articles表选择字段中。通过使用它,新字段将与其他字段一起使用。您可以在该字段上添加排序。