2016-07-25 74 views
0

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

<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); 
+0

我两个launguage multiposted(另一个是日本),因为我快点。 http://ja.stackoverflow.com/questions/27838/laravel5-1-%E3%83%AA%E3%83%AC%E3%83%BC%E3%82%B7%E3%83%A7% E3%83%B3-eloquentorm-%E5%A4%9A%E5%AF%BE%E5%A4%9A-%E3%82%BD%E3%83%BC%E3%83%88 –

回答

0

试试这个变种:

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

感谢您的回答: ) 但什么都没有发生:( –