spAo's avatar
Level 1

Getting pivot table data

Hello all! 0

I have Articles table and it haves category_id witch is related to AllCategories table. But now i added + articles_categories pivot table. Now i', adding one category with category_id and multi categories with pivot table.

    public function category($slug, $page = 1)
    {
        $offsetPage = ($page - 1);
        $perPage = 24;
        $category = AllCategory::bySlug($slug);
        if (!$category) {
            abort(404);
        }
        $pivot = $category->manyArticles()->get();
      
        $categoryArticles = $category->articles()->skip($perPage * $offsetPage)->take($perPage)->get();
        $lastPage = ceil($category->articles()->count() / $perPage);
        return view('pages/category')
            ->with('category', $category)
            ->with('perPage', $perPage)
            ->with('page', $page)
            ->with('lastPage', $lastPage)
            ->with('categoryArticles', $categoryArticles)
            ->with('pivot', $pivot);
    }

In $categoryArticles i'm getting articles with category_id. I cant get pivot categories with

$category->manyArticles()->get(); 

But what to do with pagination then? i need single category articles and multi category articles in single variable.

blade

  @foreach($categoryArticles as $article)
 @if(!empty($article->getUrl()))
                    <a class="w-100" href="{{$article->getUrl()}}">
                        @if(!empty($article->title))
                        <div class="w-100 font-size-14 font-size-md-12 font-size-xs-12 font-medium-caps text-blue-100 pt-15px pt-xs-5px crop-2 crop-xs-4 pr-35px pr-xs-15px h-55px h-md-50px h-xs-75px">{{$article->tr('title')}}</div>
                        @endif
                    </a>
                    @endif
                    <div class="d-flex pt-20px pt-xs-5px justify-content-between">
                        <div class="d-flex align-items-center">
                            <span class="fas fa-calendar text-light-black font-size-14 font-size-sm-13 pr-5px"></span>
                            @if(!empty($article->published_at))
                            <div class="font-base font-size-13 font-size-sm-12 mt-2px mt-sm-2px text-light-black">{{Carbon\Carbon::parse($article->published_at)->format('d/m/Y')}}
                            </div>
                            @endif
                        </div>
                    </div>
        @endforeach

What to do : /

0 likes
25 replies
spAo's avatar
Level 1

@furqanDev Yes but i have in category model

 public function articles()
    {
        return $this->hasMany(Article::class, 'category_id', 'id')->orderBy('published_at', 'Desc');
    }
    public function manyArticles()
    {
        return $this->belongsToMany(Article::class, 'articles_categories', 'category_id', 'article_id')
                ->using(ArticleCategory::class);
    }

i need them both but in $categoryArticles i'm getting only category_id categories not pivot table categories how can i get both?

spAo's avatar
Level 1

@furqanDev articles() is single category relationship and manyArticles() is pivot relationship. when user is adding article he must choose single category and if he wants he can + choose multi categories. and this function works but problem is that in categories page i display only single category articles but i also want to display pivot categories.

furqanDev's avatar

@spAo I get your point. I'm saying that did you define pivot table reverse relation in category model ?

spAo's avatar
Level 1

@furqanDev You mean article model

    public function category()
    {
        return $this->belongsTo(AllCategory::class, 'category_id', 'id');
    }

    public function manyCategories()
    {
        return $this->belongsToMany(AllCategory::class, 'articles_categories', 'article_id', 'category_id')
                ->using(ArticleCategory::class);
    }

and ArticleCategory pivot model

    public $table = 'articles_categories';

    protected $fillable = [
        'article_id', 'category_id'
    ];

    protected $guarded = ['*'];
spAo's avatar
Level 1

@furqanDev yes i did

use Illuminate\Database\Eloquent\Relations\Pivot;

class ArticleCategory extends Pivot
furqanDev's avatar

@spAo Try loading your relation like this,

$pivot = $category->load('manyArticles')->get();
spAo's avatar
Level 1

@furqanDev I'm getting All categories. but i need articles with single and multi categories in $categoryArticles variable

furqanDev's avatar

@spAo Check in relation if you are getting all related articles or not.

spAo's avatar
Level 1

@furqanDev I'm not getting articles i'm just getting all categories only categories

furqanDev's avatar

@spAo Are you getting single category while fetching this ?

$category = AllCategory::bySlug($slug);
furqanDev's avatar

@spAo Did you check in the relation section when you dd() ?

$pivot = $category->load('manyArticles')->get();
dd($pivot);
spAo's avatar
Level 1

@furqanDev I checked with dd and i'm getting all categories from ' all_categories ' table. #relations: []

furqanDev's avatar

@spAo Do you have any additional condition in ArticleCategory class ?

spAo's avatar
Level 1

@furqanDev no only

class ArticleCategory extends Pivot
{
    use HasFactory;

    public $table = 'articles_categories';

    protected $fillable = [
        'article_id', 'category_id'
    ];

    protected $guarded = ['*'];
}
furqanDev's avatar

@spAo You are over complicating a simple thing. Just go for a simple manyToMany relation between Article and Category. You can either save 0, 1 or many in pivot table. Even if you get the categories and articles you need to merge both in order to show them and make pagination. Just go for simple approach of Many to Many relation.

spAo's avatar
Level 1

@furqanDev Yes but this project is already in live and single category is already used. because of it i need both of them...

furqanDev's avatar

@spAo Then I'd suggest you to clear some code and go for simple many to many. Don't use any pivot class as you will not be doing any additional thing. In AllCategory model

public function manyArticles()
{
	return $this->belongsToMany(Article::class);
}

In Article Model

public function manyCategories()
{
	return $this->belongsToMany(AllCategory::class);
}
spAo's avatar
Level 1

@furqanDev You are saying that there is no any way to have both of them? a single category and multi?

furqanDev's avatar

@spAo Yes it is. I just told you to don't overwrite the code. You can simply do this. Without any pivot class since you don't have any additional methods you just go for the simple approach.

spAo's avatar
Level 1

@furqanDev I'm getting to many errors... it's not a option to me... I think it's passable to have both. Okay i will continue to search. Thanks for your time : )

spAo's avatar
spAo
OP
Best Answer
Level 1

@furqanDev I found the way!

  $offsetPage = ($page - 1);
        $perPage = 24;
        $category = AllCategory::bySlug($slug);
        if (!$category) {
            abort(404);
        }
        $ids_from_main_category = $category->articles()->pluck('id')->toArray();
        $ids_from_pivot = $category->manyArticles()->pluck('articles.id')->toArray();
        $both_ids = array_merge($ids_from_pivot, $ids_from_main_category);
        $articles = Article::whereIn('id', $both_ids)->publishedOrder()->statusOn();
        $categoryArticles = $articles->skip($perPage * $offsetPage)->take($perPage)->get();
        $lastPage = ceil($category->articles()->count() / $perPage);

This code is doing does exactly what I wanted. : )

Please or to participate in this conversation.