I am creating a blog CMS using Laravel 5.2. In my application there is a one-to-many relationship between posts and categories, where a post has one category.
My posts table has a 'category_id' attribute that links to the categories table 'id' attribute.
On my categories index page I have a table allowing users to delete categories or add more, and would like to include a column on this table that has the number of posts in each category. I have considered rolling back my migrations and adding a num_posts attribute to the categories table, but I feel like there is a better way.
My solution was to add the following function to the Category model:
public static function allWithCount()
{
// grab all categories and posts
$categories = Category::orderBy('id')->get();
$posts = Post::all();
// create new categories array with num_posts attribute
$categoriesArray = [];
for($i = 0; $i < count($categories); $i++)
{
$counter = 0;
foreach($posts as $post)
{
if($categories[$i]->id == $post->category_id)
{
$counter++;
}
}
// copy the category over to the new array with $counter
$categoriesArray[$i]['id'] = $categories[$i]->id;
$categoriesArray[$i]['category'] = $categories[$i]->category;
$categoriesArray[$i]['num_posts'] = $counter;
}
return $categoriesArray;
}
This function achieved what I want it to do, but now I have another problem. I have a many-to-many relationship between tags and posts. Tag's index is almost identical to the categories index, including needing a number of posts column. Now I'm in a position where I'm copying a function from one model to another, which I know is terrible practice and will result in brittle code.
Now that I'm in this position I know that there must be a better way to go about this. Should I just include a num_posts attribute in my tags and categories tables? Is there already an eloquent function that achieves my goal (a google search didn't result in anything)?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2s4SHOG
via IFTTT
Aucun commentaire:
Enregistrer un commentaire