Laravel5.1,关系,EloquentORM,多对多,排序

时间:2016-07-25 03:06:01

标签: laravel laravel-5 laravel-5.1

<table border="true">
  <tr>
    <th style="width:100px">Table</th>
    <th colspan="3" style="width:300px">Columns</th>
  </tr>
  <tr>
    <td style="width:100px">Articles</td>
    <td style="width:100px">id</td>
    <td colspan="2" style="width:200px; color: #aaaaaa">other dependent variables</td>
  </tr>
  <tr>
    <td style="width:100px">Article_Tag</td>
    <td style="width:100px">id</td>
    <td style="width:100px">article_id</td>
    <td style="width:100px">tag_id</td>
  </tr>
  <tr>
    <td style="width:100px">Tags</td>
    <td style="width:100px">id</td>
    <td style="width:100px">name</td>
    <td style="width:100px"></td>
  </tr>
</table>

然后,我想按标签表的[名称]对文章表进行排序。 我尝试用下面的封口加载,但它没有用。 模型文章和标签只是由belongsToMany相互连接, 我成功输出了他们的数据,但是他们没有排序。事实上,我没有给getTag任何论据。(当我给出论证时,他们也没有被[名字]缩小。)

use App\Article;
use App\Tag;

...

public function __construct(Article $article)
{
  $this->article = $article;
}

...

public function getTag($tag = NULL)
{  
$flag = isset($tag);

$articles = $this->article->orderBy('created_at', 'desc')->with([
    'tags' => function($query) use ($flag, $tag){
        ($flag)
            ? $query->where('name', $tag)
            : $query->orderBy('name');
    }
])->paginate(15);

1 个答案:

答案 0 :(得分:0)

尝试此变体:

$articles = $this->article->with([
    'tags' => function($query) use ($flag, $tag){
        return $flag
            ? $query->where("name", $tag);
            : $query->orderBy("name")        
    }
])->paginate(15);