dimanche 24 juillet 2016

Laravel5.1, Relation, EloquentORM, Many to Many, Sort

<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>

Then, I want to sort Articles table by [name] of Tags table. I tried eager-loading with closure below, but it did'nt work. Model Article and Tag are connected with each other just by belongsToMany, and I succeed in output their data, but they weren't sorted.Offcourse, I did'nt give getTag any argument.

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire